Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
af999d8a11 | ||
|
|
9f5493185d | ||
|
|
4cd987eef6 | ||
|
|
19f43e8018 | ||
|
|
3f13bb5b46 | ||
|
|
eb0466245b | ||
|
|
ce80867d09 | ||
|
|
1921959fc1 | ||
|
|
d5e76dee36 | ||
|
|
b476b58a91 | ||
|
|
ca32191c77 | ||
|
|
7f1d5dfbcd | ||
|
|
7e4a2037d8 | ||
|
|
f434402530 | ||
|
|
1fc9976ca3 | ||
|
|
cafce5cfa9 | ||
|
|
a3420c5266 | ||
|
|
3b771fc0b6 | ||
|
|
0b083cfdbd | ||
|
|
53efa7e14e | ||
|
|
d6af566601 | ||
|
|
25876f94bd | ||
|
|
1cf8ff40bd | ||
|
|
70d7435b5f | ||
|
|
a451951e7a | ||
|
|
053ea392f2 | ||
|
|
1dc5a459b3 | ||
|
|
6e78c10171 |
No files matched your search
@@ -89,10 +89,10 @@ SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS=30
|
||||
SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN={task_no}-{date}.xlsx
|
||||
|
||||
# RPA 目录(相对 backend/ 根目录)
|
||||
FREIGHT_INVENTORY_DROP_DIR=data/freight_rpa/inventory_drop
|
||||
FREIGHT_RPA_INVENTORY_TRIGGER_DIR=data/freight_rpa/inventory_triggers
|
||||
FREIGHT_UPLOAD_QUEUE_DIR=data/freight_rpa/upload_queue
|
||||
FREIGHT_RPA_UPLOAD_TRIGGER_DIR=data/freight_rpa/upload_triggers
|
||||
FREIGHT_INVENTORY_DROP_DIR=data/shipping_notice/freight_rpa/inventory_drop
|
||||
FREIGHT_RPA_INVENTORY_TRIGGER_DIR=data/shipping_notice/freight_rpa/inventory_triggers
|
||||
FREIGHT_UPLOAD_QUEUE_DIR=data/shipping_notice/freight_rpa/upload_queue
|
||||
FREIGHT_RPA_UPLOAD_TRIGGER_DIR=data/shipping_notice/freight_rpa/upload_triggers
|
||||
|
||||
# 发货 Excel 模板(可选)
|
||||
FREIGHT_SHIPMENT_TEMPLATE_PATH=templates/freight_shipment_upload.xlsx
|
||||
|
||||
+1
-1
@@ -28,7 +28,7 @@ EDKB_SOFFICE_TIMEOUT_SEC=600
|
||||
# Windows Word COM / word_bridge 单次转换超时(秒);复杂 .doc 可适当放宽
|
||||
EDKB_WORD_TIMEOUT_SEC=300
|
||||
# 单文件清洗总超时(秒);超时后终止当前文件处理,避免单条任务长期卡住整个 worker
|
||||
EDKB_FILE_TIMEOUT_SEC=180
|
||||
EDKB_FILE_TIMEOUT_SEC=300
|
||||
# Word 文档(.doc/.docx)单文件清洗总超时(秒);优先于 EDKB_FILE_TIMEOUT_SEC
|
||||
EDKB_WORD_FILE_TIMEOUT_SEC=420
|
||||
# running 任务回收阈值,须大于 EDKB_SOFFICE_TIMEOUT_SEC 及整条清洗链路耗时
|
||||
|
||||
@@ -93,10 +93,10 @@ SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS=30
|
||||
SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN={task_no}-{date}.xlsx
|
||||
|
||||
# RPA 目录(相对 backend/ 根目录)
|
||||
FREIGHT_INVENTORY_DROP_DIR=data/freight_rpa/inventory_drop
|
||||
FREIGHT_RPA_INVENTORY_TRIGGER_DIR=data/freight_rpa/inventory_triggers
|
||||
FREIGHT_UPLOAD_QUEUE_DIR=data/freight_rpa/upload_queue
|
||||
FREIGHT_RPA_UPLOAD_TRIGGER_DIR=data/freight_rpa/upload_triggers
|
||||
FREIGHT_INVENTORY_DROP_DIR=data/shipping_notice/freight_rpa/inventory_drop
|
||||
FREIGHT_RPA_INVENTORY_TRIGGER_DIR=data/shipping_notice/freight_rpa/inventory_triggers
|
||||
FREIGHT_UPLOAD_QUEUE_DIR=data/shipping_notice/freight_rpa/upload_queue
|
||||
FREIGHT_RPA_UPLOAD_TRIGGER_DIR=data/shipping_notice/freight_rpa/upload_triggers
|
||||
|
||||
# 发货 Excel 模板(可选)
|
||||
FREIGHT_SHIPMENT_TEMPLATE_PATH=templates/freight_shipment_upload.xlsx
|
||||
|
||||
@@ -49,9 +49,12 @@ frontend/package-lock.json
|
||||
.vscode/*
|
||||
!.vscode/settings.json
|
||||
!.vscode/extensions.json
|
||||
.trae/*
|
||||
.cursor/*
|
||||
.idea/
|
||||
*.swp
|
||||
*.swo
|
||||
.cursorrules
|
||||
|
||||
# Runtime files
|
||||
.run/
|
||||
@@ -79,3 +82,4 @@ oracle_client/
|
||||
backend/data/kb/
|
||||
.pytest_cache/
|
||||
backend/data/fixed_assets/manifest.json
|
||||
backend/data/shipping_notice/
|
||||
Vendored
+25
-1
@@ -4,6 +4,29 @@
|
||||
"python.terminal.activateEnvironment": true,
|
||||
"python.venvPath": "${workspaceFolder}/backend",
|
||||
"python.venvFolders": [".venv"],
|
||||
"github.copilot.chat.commitMessageGeneration.instructions": [
|
||||
{
|
||||
"text": "Generate Git commit messages in Simplified Chinese by default."
|
||||
},
|
||||
{
|
||||
"text": "Follow Conventional Commits format: <type>(<scope>): <subject>."
|
||||
},
|
||||
{
|
||||
"text": "Use English for type and scope; use Simplified Chinese for subject and body."
|
||||
},
|
||||
{
|
||||
"text": "Allowed types are feat, fix, docs, style, refactor, perf, test, build, ci, chore, revert."
|
||||
},
|
||||
{
|
||||
"text": "The subject must be imperative, no period at the end, and no longer than 100 Chinese characters."
|
||||
},
|
||||
{
|
||||
"text": "Avoid vague messages such as update, fix bug, or WIP."
|
||||
},
|
||||
{
|
||||
"text": "When a body is useful, write concise Chinese bullet points describing concrete changes."
|
||||
}
|
||||
],
|
||||
|
||||
// 默认终端:加载 cd 钩子,进入 backend 时自动激活 .venv
|
||||
"terminal.integrated.defaultProfile.windows": "PowerShell (HXOPS)",
|
||||
@@ -30,5 +53,6 @@
|
||||
"Set-Location '${workspaceFolder}/backend'; if (Test-Path '.venv/Scripts/Activate.ps1') { . '.venv/Scripts/Activate.ps1' }"
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"js/ts.tsdk.path": "node_modules\\typescript\\lib"
|
||||
}
|
||||
@@ -5,8 +5,6 @@ FROM ${PYTHON_BASE_IMAGE}
|
||||
ARG APT_MIRROR=https://mirrors.aliyun.com
|
||||
ARG PIP_INDEX_URL=https://mirrors.aliyun.com/pypi/simple
|
||||
ARG PIP_EXTRA_INDEX_URL
|
||||
ARG PIP_TIMEOUT=300
|
||||
ARG PIP_RETRIES=15
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
|
||||
+12
-44
@@ -1,21 +1,21 @@
|
||||
"""
|
||||
backend/app/__init__.py
|
||||
应用工厂:创建 Flask 应用、注册蓝图并挂载全局异常与响应处理。
|
||||
|
||||
用途:应用工厂:创建 Flask 应用、挂载全局异常与响应处理。
|
||||
依赖:app.extensions(db、migrate)、app.api.register_blueprints、app.core.config。
|
||||
逻辑:create_app 初始化扩展后委托 api 层集中注册 Blueprint;models/services 仍可通过 from app import db 引用。
|
||||
"""
|
||||
import logging
|
||||
import uuid
|
||||
|
||||
from flask import Flask, jsonify, request, g
|
||||
from flask_sqlalchemy import SQLAlchemy
|
||||
from flask_migrate import Migrate
|
||||
from flask_cors import CORS
|
||||
from werkzeug.exceptions import HTTPException
|
||||
from app.config import config
|
||||
from app.errors import AppError
|
||||
from app.response_utils import error_payload, utc_iso_now
|
||||
|
||||
db = SQLAlchemy()
|
||||
migrate = Migrate()
|
||||
from app.core.config.settings import config
|
||||
from app.core.errors import AppError
|
||||
from app.extensions import db, migrate
|
||||
from app.core.response import error_payload, utc_iso_now
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -27,7 +27,7 @@ def _apply_persisted_settings(app: Flask) -> None:
|
||||
common case where the table does not yet exist (fresh deploy before
|
||||
``flask db upgrade`` runs).
|
||||
"""
|
||||
from app.env_persistence import apply_env_settings
|
||||
from app.core.config.env_persistence import apply_env_settings
|
||||
|
||||
try:
|
||||
applied = apply_env_settings()
|
||||
@@ -46,42 +46,9 @@ def create_app(config_name='default'):
|
||||
migrate.init_app(app, db)
|
||||
CORS(app) # 允许跨域
|
||||
|
||||
# 注册 Blueprints
|
||||
from app.api.chat import chat_bp
|
||||
from app.api.admin import admin_bp
|
||||
from app.api.agents import agents_bp
|
||||
from app.api.user import user_bp
|
||||
from app.api.knowledge_base import knowledge_base_bp
|
||||
from app.api.integration import integration_bp
|
||||
from app.api.schedule_admin import schedule_admin_bp
|
||||
from app.api.workspace_schedule import workspace_schedule_bp
|
||||
from app.api.workspace_shipping_notice import workspace_shipping_notice_bp
|
||||
from app.api.workspace_file_check import workspace_file_check_bp
|
||||
from app.api.internal_jobs import internal_jobs_bp
|
||||
from app.api.shipping_notice_tools import shipping_notice_bp
|
||||
from app.api.file_check_tools import file_check_bp
|
||||
from app.api.speech import speech_bp
|
||||
from app.api import register_blueprints
|
||||
|
||||
# 聊天相关接口
|
||||
app.register_blueprint(chat_bp, url_prefix='/api/chat')
|
||||
# 管理员相关接口
|
||||
app.register_blueprint(admin_bp, url_prefix='/api/admin')
|
||||
# 普通用户可见的 Agent 列表接口
|
||||
app.register_blueprint(agents_bp, url_prefix='/api/agents')
|
||||
# 当前用户相关接口(首页、常见问题等)
|
||||
app.register_blueprint(user_bp, url_prefix='/api/user')
|
||||
# 知识库数据清洗模块接口
|
||||
app.register_blueprint(knowledge_base_bp, url_prefix='/api/kb')
|
||||
# 知识库外部集成接口(供外部系统按 Dify 映射反查源文件)
|
||||
app.register_blueprint(integration_bp, url_prefix='/api/integration')
|
||||
app.register_blueprint(schedule_admin_bp, url_prefix='/api/admin')
|
||||
app.register_blueprint(workspace_schedule_bp, url_prefix='/api/workspace')
|
||||
app.register_blueprint(workspace_shipping_notice_bp, url_prefix='/api/workspace')
|
||||
app.register_blueprint(workspace_file_check_bp, url_prefix='/api/workspace')
|
||||
app.register_blueprint(internal_jobs_bp, url_prefix='/api/internal/jobs')
|
||||
app.register_blueprint(shipping_notice_bp, url_prefix='/api/shipping-notice')
|
||||
app.register_blueprint(file_check_bp, url_prefix='/api/file-check')
|
||||
app.register_blueprint(speech_bp, url_prefix='/api/speech')
|
||||
register_blueprints(app)
|
||||
|
||||
# Eagerly load persisted runtime settings so the very first request after
|
||||
# a worker boot already sees the admin-saved configuration (otherwise the
|
||||
@@ -193,6 +160,7 @@ def create_app(config_name='default'):
|
||||
|
||||
@app.errorhandler(AppError)
|
||||
def _handle_app_error(exc: AppError):
|
||||
"""统一业务异常 → JSON error_payload(API 层应 raise AppError 而非 jsonify error)。"""
|
||||
_log_api_error(
|
||||
code=exc.code,
|
||||
message=exc.message,
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
backend/app/api/__init__.py
|
||||
|
||||
用途:集中注册所有 Blueprint(Wave 1 接入 create_app)。
|
||||
依赖:各 api 子包 blueprint。
|
||||
逻辑:替代 app/__init__.py 内 15 行散乱 register_blueprint。
|
||||
用途:集中注册所有 HTTP Blueprint。
|
||||
依赖:各 api 子模块 blueprint(单体或分包 re-export)。
|
||||
逻辑:create_app 唯一调用 register_blueprints(app);后续拆包只改本文件 import 来源。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -12,8 +12,8 @@ from flask import Flask
|
||||
|
||||
def register_blueprints(app: Flask) -> None:
|
||||
"""
|
||||
注册全部 HTTP Blueprint,保持对外 url_prefix 不变。
|
||||
核心逻辑:Wave 0 仍从既有单体模块 import;Wave 1+ 逐步切换至分包。
|
||||
注册全部 HTTP Blueprint,保持对外 url_prefix 与 Wave 0 之前一致。
|
||||
核心逻辑:集中管理路由挂载点;后续 api/user、api/chat 等分包迁移时仅改本函数 import 来源。
|
||||
Args:
|
||||
app: Flask 应用实例。
|
||||
"""
|
||||
@@ -22,12 +22,13 @@ def register_blueprints(app: Flask) -> None:
|
||||
from app.api.admin import admin_bp
|
||||
from app.api.agents import agents_bp
|
||||
from app.api.user import user_bp
|
||||
from app.api.knowledge_base import knowledge_base_bp
|
||||
from app.api.integration import integration_bp
|
||||
from app.api.internal_jobs import internal_jobs_bp
|
||||
from app.api.speech import speech_bp
|
||||
from app.api.training import training_admin_bp, training_user_bp
|
||||
|
||||
# [STEP 2] 已分包骨架(re-export 旧模块,Wave 1 可切换 import 来源)
|
||||
# [STEP 2] 已分包骨架(Wave 3:kb、schedule 等)
|
||||
from app.api.kb import knowledge_base_bp
|
||||
from app.api.schedule import schedule_admin_bp
|
||||
from app.api.workspace import (
|
||||
workspace_file_check_bp,
|
||||
@@ -40,6 +41,7 @@ def register_blueprints(app: Flask) -> None:
|
||||
app.register_blueprint(admin_bp, url_prefix='/api/admin')
|
||||
app.register_blueprint(agents_bp, url_prefix='/api/agents')
|
||||
app.register_blueprint(user_bp, url_prefix='/api/user')
|
||||
app.register_blueprint(training_user_bp, url_prefix='/api/user')
|
||||
app.register_blueprint(knowledge_base_bp, url_prefix='/api/kb')
|
||||
app.register_blueprint(integration_bp, url_prefix='/api/integration')
|
||||
app.register_blueprint(schedule_admin_bp, url_prefix='/api/admin')
|
||||
@@ -50,3 +52,4 @@ def register_blueprints(app: Flask) -> None:
|
||||
app.register_blueprint(shipping_notice_bp, url_prefix='/api/shipping-notice')
|
||||
app.register_blueprint(file_check_bp, url_prefix='/api/file-check')
|
||||
app.register_blueprint(speech_bp, url_prefix='/api/speech')
|
||||
app.register_blueprint(training_admin_bp, url_prefix='/api/admin')
|
||||
@@ -8,10 +8,10 @@ backend/app/api/admin.py
|
||||
from flask import Blueprint, request, jsonify, current_app
|
||||
from app.models import Agent, User, PermissionRequest, ChatLog, Feedback, GeneralFeedback, Department, UserFavoriteAgent, UserDefaultAgent, QuickQuestion, UserHomepageConfig, LoginAudit, WecomNotifyAudit, AgentGuide, KbDocument
|
||||
from app.services.minio_service import minio_service
|
||||
from app.decorators import require_admin
|
||||
from app.config import Config
|
||||
from app.core.decorators import require_admin
|
||||
from app.core.config.settings import Config
|
||||
from app import db
|
||||
from app.env_persistence import persist_env_settings
|
||||
from app.core.config.env_persistence import persist_env_settings
|
||||
from sqlalchemy import func, desc, inspect, or_
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.orm import joinedload
|
||||
@@ -26,8 +26,17 @@ from app.services.wecom_notify import send_wecom_event_message
|
||||
from app.services.oa_wecom_sync import sync_wecom_userids_from_oa
|
||||
from app.services.dify import DifyService
|
||||
from app.services.user_admin import delete_admin_users
|
||||
from app.auth_jwt import get_current_user as _get_auth_user
|
||||
from app.errors import AppError, ValidationError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, ServiceUnavailableError, raise_for_status
|
||||
from app.core.auth.jwt import get_current_user as _get_auth_user
|
||||
from app.core.errors import (
|
||||
AppError,
|
||||
ConflictError,
|
||||
ForbiddenError,
|
||||
NotFoundError,
|
||||
ServiceUnavailableError,
|
||||
UnauthorizedError,
|
||||
ValidationError,
|
||||
raise_for_status,
|
||||
)
|
||||
admin_bp = Blueprint('admin', __name__)
|
||||
|
||||
def _raise_user_integrity_conflict(exc: IntegrityError) -> None:
|
||||
@@ -1273,6 +1282,7 @@ def _chat_logs_report_query():
|
||||
db.session.query(
|
||||
ChatLog,
|
||||
User.username.label('username'),
|
||||
User.real_name.label('real_name'),
|
||||
Agent.name.label('agent_name'),
|
||||
)
|
||||
.join(User, User.id == ChatLog.user_id)
|
||||
@@ -1280,7 +1290,7 @@ def _chat_logs_report_query():
|
||||
)
|
||||
|
||||
|
||||
def _serialize_chat_log_report_row(log: ChatLog, username: str | None, agent_name: str | None) -> dict:
|
||||
def _serialize_chat_log_report_row(log: ChatLog, username: str | None, real_name: str | None, agent_name: str | None) -> dict:
|
||||
"""
|
||||
将 ChatLog 及关联字段序列化为报表行(隐藏 run_id / 原始 ID 类外键列)。
|
||||
保留 id 供前端批量删除使用,默认不在表格列中展示。
|
||||
@@ -1290,12 +1300,11 @@ def _serialize_chat_log_report_row(log: ChatLog, username: str | None, agent_nam
|
||||
'id': log.id,
|
||||
'agent_name': agent_name or '',
|
||||
'username': username or '',
|
||||
'real_name': real_name or '',
|
||||
'created_at': created_at,
|
||||
'query': log.query,
|
||||
'answer': log.answer,
|
||||
'session_id': log.session_id,
|
||||
'tokens_used': log.tokens_used,
|
||||
'message_type': log.message_type,
|
||||
}
|
||||
|
||||
|
||||
@@ -1311,6 +1320,8 @@ def _apply_chat_logs_report_filters(query):
|
||||
query = query.filter(Agent.name.cast(db.String).ilike(f'%{value}%'))
|
||||
elif key == 'username':
|
||||
query = query.filter(User.username.cast(db.String).ilike(f'%{value}%'))
|
||||
elif key == 'real_name':
|
||||
query = query.filter(User.real_name.cast(db.String).ilike(f'%{value}%'))
|
||||
elif hasattr(ChatLog, key):
|
||||
col = getattr(ChatLog, key)
|
||||
query = query.filter(col.cast(db.String).ilike(f'%{value}%'))
|
||||
@@ -1322,7 +1333,7 @@ def _list_chat_logs_report():
|
||||
query = _apply_chat_logs_report_filters(_chat_logs_report_query())
|
||||
query = query.order_by(desc(ChatLog.created_at), desc(ChatLog.id))
|
||||
items = query.limit(100).all()
|
||||
rows = [_serialize_chat_log_report_row(log, username, agent_name) for log, username, agent_name in items]
|
||||
rows = [_serialize_chat_log_report_row(log, username, real_name, agent_name) for log, username, real_name, agent_name in items]
|
||||
return jsonify(rows)
|
||||
|
||||
|
||||
@@ -1382,6 +1393,11 @@ def get_table_count(table):
|
||||
"""
|
||||
Return total row count for admin report tables.
|
||||
"""
|
||||
if table == 'chat_logs':
|
||||
query = _apply_chat_logs_report_filters(_chat_logs_report_query())
|
||||
total = query.count()
|
||||
return jsonify({'table': table, 'total': int(total or 0)})
|
||||
|
||||
model_map = {'users': User, 'agents': Agent, 'chat_logs': ChatLog, 'feedbacks': Feedback, 'permission_requests': PermissionRequest, 'departments': Department, 'quick_questions': QuickQuestion, 'user_homepage_configs': UserHomepageConfig, 'user_favorite_agents': UserFavoriteAgent, 'user_default_agents': UserDefaultAgent}
|
||||
model = model_map.get(table)
|
||||
if not model:
|
||||
|
||||
+15
-16
@@ -1,15 +1,18 @@
|
||||
"""
|
||||
backend/app/api/agents.py
|
||||
文件用途:普通用户可见的 Agent 列表接口
|
||||
引用文件:flask, models, decorators
|
||||
逻辑关系:根据当前用户的权限返回其可访问的 Agent 集合
|
||||
|
||||
用途:普通用户可见的 Agent 列表与 AgentGuide 静态资源。
|
||||
依赖:app.core.auth.jwt、models、minio_service。
|
||||
逻辑:按当前用户 RBAC 返回可访问 Agent;未登录 raise UnauthorizedError。
|
||||
"""
|
||||
import os
|
||||
from flask import Blueprint, jsonify, send_from_directory
|
||||
|
||||
from app import db
|
||||
from app.decorators import _get_current_user # 内部工具函数
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.errors import UnauthorizedError
|
||||
from app.models import Agent, User, AgentGuide
|
||||
from app.services.agent_category import serialize_agent_list_item, sort_agent_rows
|
||||
from app.services.minio_service import minio_service
|
||||
|
||||
# 定义 Blueprint,将在应用工厂中注册为 /api/agents
|
||||
@@ -17,13 +20,7 @@ agents_bp = Blueprint('agents', __name__)
|
||||
|
||||
|
||||
def _serialize_agent_row(row) -> dict:
|
||||
return {
|
||||
'id': row.id,
|
||||
'name': row.name,
|
||||
'description': row.description,
|
||||
'icon_url': row.icon_url,
|
||||
'dify_app_type': (row.extra_config or {}).get('dify_app_type') if hasattr(row, 'extra_config') else None,
|
||||
}
|
||||
return serialize_agent_list_item(row)
|
||||
|
||||
|
||||
@agents_bp.route('', methods=['GET'])
|
||||
@@ -33,7 +30,9 @@ def list_user_agents():
|
||||
用途:Workspace 页面展示应用网格
|
||||
"""
|
||||
# 获取当前用户(目前固定为 admin 用户,用于演示)
|
||||
user: User = _get_current_user()
|
||||
user: User = get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError()
|
||||
|
||||
# 管理员:返回所有激活的 Agent
|
||||
if user.role == 'admin':
|
||||
@@ -57,8 +56,8 @@ def list_user_agents():
|
||||
if a.is_active
|
||||
]
|
||||
|
||||
# 序列化为前端所需字段
|
||||
return jsonify([_serialize_agent_row(row) for row in agent_rows])
|
||||
# [STEP 1] 按 extra_config 分类字段排序后序列化
|
||||
return jsonify([_serialize_agent_row(row) for row in sort_agent_rows(agent_rows)])
|
||||
|
||||
@agents_bp.route('/<int:agent_id>/guides', methods=['GET'])
|
||||
def list_agent_guides(agent_id):
|
||||
@@ -66,7 +65,7 @@ def list_agent_guides(agent_id):
|
||||
获取指定应用的新手指南列表 (需登录)
|
||||
用途:客户端 Chat 界面点击新手指南
|
||||
"""
|
||||
_get_current_user() # 确保已登录
|
||||
get_current_user() # 确保已登录
|
||||
|
||||
if agent_id == 0:
|
||||
generic_agent = db.session.query(Agent).filter_by(name='通用入口').first()
|
||||
@@ -108,7 +107,7 @@ def list_public_agents():
|
||||
.order_by(Agent.id.asc())
|
||||
.all()
|
||||
)
|
||||
return jsonify([_serialize_agent_row(row) for row in agent_rows])
|
||||
return jsonify([_serialize_agent_row(row) for row in sort_agent_rows(agent_rows)])
|
||||
|
||||
# 为了兼容本地无MinIO的环境,暴露一个静态文件读取接口
|
||||
@agents_bp.route('/guides/files/<path:filename>', methods=['GET'])
|
||||
|
||||
+66
-14
@@ -1,8 +1,9 @@
|
||||
"""
|
||||
backend/app/api/chat.py
|
||||
文件用途:定义聊天相关 API 路由
|
||||
引用文件:flask, services.dify, decorators, models
|
||||
逻辑关系:作为前端与 Dify 之间的 BFF 层,负责转发请求并流式返回结果
|
||||
|
||||
用途:聊天 BFF(SSE 流式、会话 CRUD、PLM/Excel 预览、反馈)。
|
||||
依赖:app.core.decorators、app.core.errors、services.dify、integrations。
|
||||
逻辑:/completions 按意图分流(Wave 3 抽至 services/chat/router.py);错误统一 raise AppError。
|
||||
"""
|
||||
import io
|
||||
import ipaddress
|
||||
@@ -21,13 +22,23 @@ from sqlalchemy import func, desc, or_, exists, and_
|
||||
from openpyxl import load_workbook
|
||||
from app.services.dify import DifyService
|
||||
from app.services.integration_api import IntegrationApiService
|
||||
from app.decorators import require_agent_permission
|
||||
from app.core.decorators import require_agent_permission
|
||||
from app.models import Agent, ChatLog, ChatSession, Feedback
|
||||
from app import db
|
||||
from app.errors import AppError, ValidationError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, ServiceUnavailableError, raise_for_status
|
||||
from app.core.errors import (
|
||||
AppError,
|
||||
ConflictError,
|
||||
ForbiddenError,
|
||||
NotFoundError,
|
||||
ServiceUnavailableError,
|
||||
UnauthorizedError,
|
||||
ValidationError,
|
||||
raise_for_status,
|
||||
)
|
||||
chat_bp = Blueprint('chat', __name__)
|
||||
|
||||
LEAVE_FEATURE_AGENT_NAMES = {'通用入口', '人事规章'}
|
||||
SHIPPING_NOTICE_AGENT_NAME = '货代发货通知 Agent'
|
||||
|
||||
|
||||
def _can_use_leave_feature(agent_proxy) -> bool:
|
||||
@@ -42,6 +53,28 @@ def _session_title_from_text(text: str) -> str:
|
||||
return value[:30] + ('...' if len(value) > 30 else '')
|
||||
|
||||
|
||||
def _user_facing_chat_query(text: str, agent_name: str | None = None) -> str:
|
||||
"""
|
||||
将内部 Agent 编排提示转换成业务用户可见话术。
|
||||
|
||||
Args:
|
||||
text: chat_logs.query 中保存的用户侧文本。
|
||||
agent_name: 当前 Agent 名称,仅对发货通知 Agent 做工具名净化。
|
||||
Returns:
|
||||
可直接展示在聊天历史里的用户问题。
|
||||
"""
|
||||
value = str(text or '').strip()
|
||||
if not value or str(agent_name or '').strip() != SHIPPING_NOTICE_AGENT_NAME:
|
||||
return value
|
||||
import re
|
||||
|
||||
task_match = re.search(r'(SN-\d{8}-[A-Z0-9]+)', value, re.I)
|
||||
task_no = task_match.group(1).upper() if task_match else ''
|
||||
if 'create_task' in value or 'get_task_status' in value or 'parse_notice' in value:
|
||||
return f'继续处理当前发货任务 {task_no}'.strip()
|
||||
return value
|
||||
|
||||
|
||||
def _serialize_session(session: ChatSession) -> dict:
|
||||
last_active = session.last_active_at or session.created_at
|
||||
return {
|
||||
@@ -899,9 +932,23 @@ def get_chat_messages():
|
||||
).order_by(ChatLog.created_at.asc()).all()
|
||||
|
||||
messages = []
|
||||
agent_name = str(getattr(g.current_agent, 'name', '') or '').strip()
|
||||
for log in logs:
|
||||
if log.query:
|
||||
messages.append({'role': 'user', 'content': log.query})
|
||||
messages.append({'role': 'user', 'content': _user_facing_chat_query(log.query, agent_name)})
|
||||
if (
|
||||
not log.answer
|
||||
and not log.message_type
|
||||
and not log.payload
|
||||
):
|
||||
continue
|
||||
if (
|
||||
log.query
|
||||
and log.answer == log.query
|
||||
and (not log.message_type or log.message_type == 'text')
|
||||
and not log.payload
|
||||
):
|
||||
continue
|
||||
assistant_msg = {
|
||||
'role': 'assistant',
|
||||
'content': log.answer,
|
||||
@@ -930,10 +977,14 @@ def save_local_message():
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Missing context', http_status=500)
|
||||
data = request.get_json() or {}
|
||||
conversation_id = (data.get('conversation_id') or '').strip()
|
||||
role = (data.get('role') or 'assistant').strip()
|
||||
message_type = data.get('type')
|
||||
content = data.get('content', '')
|
||||
payload = data.get('payload')
|
||||
user_query = data.get('query', '')
|
||||
if role == 'user':
|
||||
user_query = user_query or content
|
||||
content = ''
|
||||
|
||||
if not message_type:
|
||||
raise ValidationError('type is required')
|
||||
@@ -1064,6 +1115,7 @@ def chat_completions():
|
||||
"""
|
||||
data = request.get_json() or {}
|
||||
query = data.get('query')
|
||||
display_query = str(data.get('display_query') or query or '').strip()
|
||||
# 前端传入的 conversation_id 在 B2 里代表本地 session_id
|
||||
conversation_id = data.get('conversation_id')
|
||||
shipping_task_id = str(data.get('task_id') or '').strip()
|
||||
@@ -1107,7 +1159,7 @@ def chat_completions():
|
||||
user_id,
|
||||
agent_id,
|
||||
existing_session.session_id,
|
||||
title=query,
|
||||
title=display_query,
|
||||
status='running',
|
||||
)
|
||||
external_conversation_id = session.external_conversation_id
|
||||
@@ -1116,13 +1168,13 @@ def chat_completions():
|
||||
user_id,
|
||||
agent_id,
|
||||
conversation_id,
|
||||
title=query,
|
||||
title=display_query,
|
||||
status='running',
|
||||
external_conversation_id=conversation_id,
|
||||
)
|
||||
external_conversation_id = session.external_conversation_id
|
||||
else:
|
||||
session = _ensure_chat_session(user_id, agent_id, None, title=query, status='running')
|
||||
session = _ensure_chat_session(user_id, agent_id, None, title=display_query, status='running')
|
||||
|
||||
normalized_files: list[dict] | None = None
|
||||
if files is not None:
|
||||
@@ -1189,7 +1241,7 @@ def chat_completions():
|
||||
raise ValidationError('This route does not support attachments')
|
||||
generator = HRLeaveSQLServerService.stream_chat(query, user_proxy, agent_proxy, external_conversation_id, session_id=session.session_id)
|
||||
else:
|
||||
dify_inputs: dict[str, str] | None = None
|
||||
dify_inputs: dict[str, object] | None = None
|
||||
hxops_turn_id: str | None = None
|
||||
from app.services.file_check_tools.agent_resolver import (
|
||||
agent_declares_file_check_progress,
|
||||
@@ -1220,12 +1272,11 @@ def chat_completions():
|
||||
elif is_shipping_agent:
|
||||
# [STEP 2] 发货通知 Chatflow 依赖会话级 task/batch 上下文稳定定位当前任务
|
||||
dify_inputs = build_shipping_notice_dify_inputs(
|
||||
external_conversation_id or session.session_id,
|
||||
session.session_id,
|
||||
task_id=shipping_task_id,
|
||||
batch_no=shipping_batch_no,
|
||||
entry_mode="user_chat",
|
||||
user_message=query,
|
||||
trigger_source="frontend_chat",
|
||||
request_id=request_id,
|
||||
)
|
||||
generator = DifyService.stream_chat(
|
||||
query,
|
||||
@@ -1237,6 +1288,7 @@ def chat_completions():
|
||||
hxops_turn_id=hxops_turn_id if is_file_check_agent else None,
|
||||
files=normalized_files,
|
||||
inputs=dify_inputs,
|
||||
display_query=display_query,
|
||||
)
|
||||
|
||||
def relay_stream():
|
||||
@@ -1352,7 +1404,7 @@ def upload_chat_file():
|
||||
raise ValidationError('file is required')
|
||||
|
||||
from app.services.dify import DifyService
|
||||
from app.config import Config
|
||||
from app.core.config.settings import Config
|
||||
|
||||
params = DifyService.get_app_parameters(agent, force_refresh=True)
|
||||
file_upload_cfg = (params or {}).get('file_upload') if isinstance(params, dict) else {}
|
||||
|
||||
@@ -17,7 +17,14 @@ from sqlalchemy import text
|
||||
|
||||
from app import db
|
||||
from app.api.workspace_file_check import serialize_file_judgement
|
||||
from app.errors import AppError, ConflictError, NotFoundError, ServiceUnavailableError, UnauthorizedError, ValidationError
|
||||
from app.core.errors import (
|
||||
AppError,
|
||||
ConflictError,
|
||||
NotFoundError,
|
||||
ServiceUnavailableError,
|
||||
UnauthorizedError,
|
||||
ValidationError,
|
||||
)
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
from app.services.file_check_tools.openapi_spec import build_file_check_openapi_spec
|
||||
from app.services.hxops_tool_api import resolve_HXOPS_TOOLS_API_BASE
|
||||
|
||||
@@ -9,7 +9,16 @@ from sqlalchemy import func
|
||||
from sqlalchemy.orm import joinedload
|
||||
from app import db
|
||||
from app.models import KbDifySyncRecord, KbDocument, KbDocumentVersion, KbGroup
|
||||
from app.errors import AppError, ValidationError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, ServiceUnavailableError, raise_for_status
|
||||
from app.core.errors import (
|
||||
AppError,
|
||||
ConflictError,
|
||||
ForbiddenError,
|
||||
NotFoundError,
|
||||
ServiceUnavailableError,
|
||||
UnauthorizedError,
|
||||
ValidationError,
|
||||
raise_for_status,
|
||||
)
|
||||
from app.services.integration_api import IntegrationApiService
|
||||
integration_bp = Blueprint('integration', __name__)
|
||||
|
||||
|
||||
@@ -6,7 +6,16 @@ from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
from app.services.schedule import _run_generic_check_job
|
||||
from app.services.schedule.dify_snapshot import capture_dify_execution_snapshot
|
||||
from app.errors import AppError, ValidationError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, ServiceUnavailableError, raise_for_status
|
||||
from app.core.errors import (
|
||||
AppError,
|
||||
ConflictError,
|
||||
ForbiddenError,
|
||||
NotFoundError,
|
||||
ServiceUnavailableError,
|
||||
UnauthorizedError,
|
||||
ValidationError,
|
||||
raise_for_status,
|
||||
)
|
||||
internal_jobs_bp = Blueprint('internal_jobs', __name__)
|
||||
|
||||
@internal_jobs_bp.route('/<name>', methods=['POST'])
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
"""
|
||||
backend/app/api/kb/__init__.py
|
||||
|
||||
用途:知识库管理 Blueprint 入口(Wave 3 分包)。
|
||||
依赖:kb/blueprint.py、common、dify、groups、documents、jobs。
|
||||
逻辑:import 子模块注册路由;register_blueprints 从本包 import knowledge_base_bp。
|
||||
"""
|
||||
from app.api.kb.blueprint import knowledge_base_bp
|
||||
|
||||
import app.api.kb.common # noqa: F401
|
||||
import app.api.kb.dify # noqa: F401
|
||||
import app.api.kb.groups # noqa: F401
|
||||
import app.api.kb.documents # noqa: F401
|
||||
import app.api.kb.jobs # noqa: F401
|
||||
|
||||
__all__ = ['knowledge_base_bp']
|
||||
@@ -0,0 +1,10 @@
|
||||
"""
|
||||
backend/app/api/kb/blueprint.py
|
||||
|
||||
用途:知识库 API 共享 Blueprint(Wave 3 分包后各子模块共用)。
|
||||
依赖:Flask Blueprint。
|
||||
逻辑:kb/dify、groups、documents、jobs 等子模块在此 bp 上注册路由;__init__ 导出 knowledge_base_bp。
|
||||
"""
|
||||
from flask import Blueprint
|
||||
|
||||
knowledge_base_bp = Blueprint('knowledge_base', __name__)
|
||||
@@ -0,0 +1,73 @@
|
||||
"""
|
||||
backend/app/api/kb/common.py
|
||||
|
||||
用途:知识库 API 共享 helper(鉴权、序列化、Markdown 预览)。
|
||||
依赖:app.core.*、models、services/kb/storage、edkb_system。
|
||||
逻辑:dify/groups/documents/jobs 子模块共用;存储读写见 services/kb/storage。
|
||||
"""
|
||||
from flask import current_app
|
||||
from sqlalchemy.exc import DatabaseError, OperationalError
|
||||
|
||||
from app import db
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.errors import UnauthorizedError
|
||||
from app.models import KbDifySyncRecord, KbDocument, KbDocumentVersion, KbGroup
|
||||
from app.services.kb.markdown import (
|
||||
markdown_unavailable_message,
|
||||
resolve_markdown_read_path,
|
||||
resolve_markdown_write_path,
|
||||
serialize_markdown_payload,
|
||||
)
|
||||
from app.services.kb.storage import (
|
||||
kb_storage_root,
|
||||
resolve_storage_path,
|
||||
safe_upload_filename,
|
||||
save_upload,
|
||||
)
|
||||
|
||||
def require_user():
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError()
|
||||
return user
|
||||
|
||||
def run_db_read(label: str, loader):
|
||||
try:
|
||||
return loader()
|
||||
except (OperationalError, DatabaseError) as exc:
|
||||
current_app.logger.warning('[kb] transient db error during %s, retry with reconnect: %s', label, exc)
|
||||
db.session.rollback()
|
||||
db.session.remove()
|
||||
try:
|
||||
db.engine.dispose()
|
||||
except Exception:
|
||||
current_app.logger.warning('[kb] failed to dispose engine during %s recovery', label, exc_info=True)
|
||||
return loader()
|
||||
|
||||
def serialize_group(group: KbGroup, document_count: int=0):
|
||||
return {'id': group.id, 'name': group.name, 'description': group.description, 'department_id': group.department_id, 'document_count': int(document_count or 0), 'created_at': group.created_at.isoformat() if group.created_at else None, 'updated_at': group.updated_at.isoformat() if group.updated_at else None}
|
||||
|
||||
def serialize_document(doc: KbDocument):
|
||||
latest_version = current_version(doc)
|
||||
return {'id': doc.id, 'group_id': doc.group_id, 'title': doc.title, 'description': doc.description, 'status': doc.status, 'source_type': doc.source_type, 'created_at': doc.created_at.isoformat() if doc.created_at else None, 'updated_at': doc.updated_at.isoformat() if doc.updated_at else None, 'version_count': len(doc.versions) if getattr(doc, 'versions', None) else 0, 'latest_version': serialize_version(latest_version) if latest_version else None}
|
||||
|
||||
def serialize_version(version: KbDocumentVersion | None):
|
||||
if version is None:
|
||||
return None
|
||||
return {'id': version.id, 'document_id': version.document_id, 'version_no': version.version_no, 'status': version.status, 'is_current': version.is_current, 'source_file_name': version.source_file_name, 'source_file_ext': version.source_file_ext, 'source_file_size': version.source_file_size, 'sha256': version.sha256, 'cleaned_file_path': version.cleaned_file_path, 'cleaned_preview_path': version.cleaned_preview_path, 'error_message': version.error_message, 'created_at': version.created_at.isoformat() if version.created_at else None}
|
||||
|
||||
def serialize_sync_record(record: KbDifySyncRecord):
|
||||
return {'id': record.id, 'group_id': record.group_id, 'document_id': record.document_id, 'document_version_id': record.document_version_id, 'dataset_id': record.dataset_id, 'dataset_name': record.dataset_name, 'remote_document_id': record.remote_document_id, 'remote_document_name': record.remote_document_name, 'status': record.status, 'sync_hash': record.sync_hash, 'error_message': record.error_message, 'synced_at': record.synced_at.isoformat() if record.synced_at else None, 'updated_at': record.updated_at.isoformat() if record.updated_at else None}
|
||||
|
||||
def current_version(document: KbDocument | None) -> KbDocumentVersion | None:
|
||||
versions = list(getattr(document, 'versions', []) or [])
|
||||
if not versions:
|
||||
return None
|
||||
return next((item for item in versions if item.is_current), versions[0])
|
||||
|
||||
|
||||
def next_version_no(document: KbDocument) -> int:
|
||||
versions = list(getattr(document, 'versions', []) or [])
|
||||
if not versions:
|
||||
return 1
|
||||
return max((item.version_no for item in versions)) + 1
|
||||
@@ -0,0 +1,45 @@
|
||||
"""
|
||||
backend/app/api/kb/dify.py
|
||||
|
||||
用途:知识库 Dify 连接配置与健康检查 API。
|
||||
依赖:kb.blueprint、knowledge_cleaning.settings_service。
|
||||
逻辑:管理员读写 Dify 设置;GET /dify/health 探测远端 dataset。
|
||||
"""
|
||||
from flask import jsonify, request
|
||||
|
||||
from app.api.kb.blueprint import knowledge_base_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.services.knowledge_cleaning.settings_service import (
|
||||
get_kb_dify_health_payload,
|
||||
get_kb_dify_settings,
|
||||
save_kb_dify_settings,
|
||||
)
|
||||
|
||||
@knowledge_base_bp.route('/dify/settings', methods=['GET'])
|
||||
@require_admin
|
||||
def get_dify_settings():
|
||||
payload = get_kb_dify_settings()
|
||||
return jsonify(payload)
|
||||
|
||||
@knowledge_base_bp.route('/dify/settings', methods=['PATCH'])
|
||||
@require_admin
|
||||
def update_dify_settings():
|
||||
data = request.get_json(silent=True) or {}
|
||||
payload = save_kb_dify_settings(data)
|
||||
return jsonify(payload)
|
||||
|
||||
@knowledge_base_bp.route('/dify/health', methods=['GET'])
|
||||
@require_admin
|
||||
def get_dify_health():
|
||||
payload = get_kb_dify_health_payload()
|
||||
if payload['dify_api_configured'] and payload['dify_base_url']:
|
||||
try:
|
||||
from app.services.knowledge_cleaning.dify_sync_service import KbDifySyncService
|
||||
datasets = KbDifySyncService().list_datasets()
|
||||
payload['api']['reachable'] = True
|
||||
payload['api']['dataset_count'] = len(datasets)
|
||||
except Exception as exc:
|
||||
payload['api']['error'] = str(exc)
|
||||
else:
|
||||
payload['api']['error'] = 'Dify 连接尚未配置'
|
||||
return jsonify(payload)
|
||||
@@ -0,0 +1,113 @@
|
||||
"""
|
||||
backend/app/api/kb/documents.py
|
||||
|
||||
用途:知识库文档版本、Markdown、上传/清洗/同步 API(薄路由层)。
|
||||
依赖:kb.blueprint、kb.common、services/kb/document_service。
|
||||
逻辑:/documents* 与 /document-versions* 路由;业务见 document_service。
|
||||
"""
|
||||
from flask import jsonify, request, send_file
|
||||
|
||||
from app import db
|
||||
from app.api.kb.blueprint import knowledge_base_bp
|
||||
from app.api.kb.common import require_user, serialize_document, serialize_sync_record, serialize_version
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.decorators import require_admin
|
||||
from app.services.kb import document_service
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/documents/<int:document_id>/versions', methods=['GET'])
|
||||
def list_document_versions(document_id: int):
|
||||
require_user()
|
||||
versions = document_service.list_document_versions(document_id)
|
||||
return jsonify([serialize_version(item) for item in versions])
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/document-versions/<int:version_id>/source-file', methods=['GET'])
|
||||
def get_document_version_source_file(version_id: int):
|
||||
require_user()
|
||||
source_path, filename = document_service.resolve_source_file_path(version_id)
|
||||
as_attachment = str(request.args.get('download') or '').strip() == '1'
|
||||
return send_file(source_path, as_attachment=as_attachment, download_name=filename)
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/documents/<int:document_id>/sync-records', methods=['GET'])
|
||||
def list_document_sync_records(document_id: int):
|
||||
require_user()
|
||||
records = document_service.list_sync_records(document_id)
|
||||
return jsonify([serialize_sync_record(item) for item in records])
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/documents/<int:document_id>/markdown', methods=['GET'])
|
||||
def get_document_markdown(document_id: int):
|
||||
require_user()
|
||||
return jsonify(document_service.read_markdown(document_id))
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/documents/<int:document_id>/markdown', methods=['PATCH'])
|
||||
def update_document_markdown(document_id: int):
|
||||
current_user = require_user()
|
||||
data = request.get_json(silent=True) or {}
|
||||
payload = document_service.update_markdown(
|
||||
document_id,
|
||||
data.get('content'),
|
||||
user_id=getattr(current_user, 'id', None),
|
||||
)
|
||||
db.session.commit()
|
||||
return jsonify(payload)
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/documents/<int:document_id>/upload', methods=['POST'])
|
||||
def upload_document_version(document_id: int):
|
||||
current_user = require_user()
|
||||
uploaded = request.files.get('file')
|
||||
payload = document_service.upload_new_version(
|
||||
document_id,
|
||||
uploaded,
|
||||
user_id=getattr(current_user, 'id', None),
|
||||
)
|
||||
return jsonify(payload), 201
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/documents/<int:document_id>/clean', methods=['POST'])
|
||||
@require_admin
|
||||
def submit_document_clean(document_id: int):
|
||||
current_user = get_current_user()
|
||||
payload, status_code = document_service.submit_clean(
|
||||
document_id,
|
||||
user_id=getattr(current_user, 'id', None),
|
||||
)
|
||||
return jsonify(payload), status_code
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/documents/<int:document_id>/sync', methods=['POST'])
|
||||
@require_admin
|
||||
def sync_document(document_id: int):
|
||||
current_user = get_current_user()
|
||||
payload = document_service.submit_sync(
|
||||
document_id,
|
||||
user_id=getattr(current_user, 'id', None),
|
||||
)
|
||||
return jsonify(payload), 202
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/documents/<int:document_id>', methods=['PATCH'])
|
||||
def update_document(document_id: int):
|
||||
current_user = require_user()
|
||||
data = request.get_json(silent=True) or {}
|
||||
document = document_service.update_metadata(
|
||||
document_id,
|
||||
data,
|
||||
user_id=getattr(current_user, 'id', None),
|
||||
)
|
||||
db.session.commit()
|
||||
return jsonify(serialize_document(document))
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/documents/<int:document_id>', methods=['DELETE'])
|
||||
def delete_document(document_id: int):
|
||||
current_user = require_user()
|
||||
result = document_service.delete_document(
|
||||
document_id,
|
||||
user_id=getattr(current_user, 'id', None),
|
||||
)
|
||||
return jsonify(result)
|
||||
@@ -0,0 +1,292 @@
|
||||
"""
|
||||
backend/app/api/kb/groups.py
|
||||
|
||||
用途:知识库分组 CRUD、组内文档列表与路径批量上传 API(薄路由)。
|
||||
依赖:kb.blueprint、kb.common、services/kb/path_upload_service、services/kb/job_lifecycle。
|
||||
逻辑:/groups* 与 /path-upload-jobs*;业务编排委托 path_upload_service。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import jsonify, request
|
||||
from sqlalchemy import func
|
||||
from sqlalchemy.orm import joinedload
|
||||
|
||||
from app import db
|
||||
from app.api.kb.blueprint import knowledge_base_bp
|
||||
from app.api.kb.common import require_user, run_db_read, serialize_document, serialize_group
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.decorators import require_admin
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.models import KbDocument, KbGroup, KbJob
|
||||
from app.services.kb import path_upload_service
|
||||
from app.services.kb.job_lifecycle import cancel_active_kb_jobs_for_group, serialize_job
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/groups', methods=['GET'])
|
||||
def list_groups():
|
||||
require_user()
|
||||
document_counts = (
|
||||
db.session.query(KbDocument.group_id.label('group_id'), func.count(KbDocument.id).label('document_count'))
|
||||
.filter(KbDocument.is_deleted.is_(False))
|
||||
.group_by(KbDocument.group_id)
|
||||
.subquery()
|
||||
)
|
||||
rows = run_db_read(
|
||||
'list_groups',
|
||||
lambda: db.session.query(KbGroup, func.coalesce(document_counts.c.document_count, 0).label('document_count'))
|
||||
.outerjoin(document_counts, document_counts.c.group_id == KbGroup.id)
|
||||
.filter(KbGroup.is_active.is_(True))
|
||||
.order_by(KbGroup.updated_at.desc(), KbGroup.id.desc())
|
||||
.all(),
|
||||
)
|
||||
return jsonify([serialize_group(group, document_count) for group, document_count in rows])
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/groups', methods=['POST'])
|
||||
@require_admin
|
||||
def create_group():
|
||||
data = request.get_json(silent=True) or {}
|
||||
name = str(data.get('name') or '').strip()
|
||||
description = str(data.get('description') or '').strip() or None
|
||||
department_id = data.get('department_id')
|
||||
if not name:
|
||||
raise ValidationError('name is required')
|
||||
existing_query = db.session.query(KbGroup).filter(KbGroup.name == name, KbGroup.is_active.is_(True))
|
||||
if department_id is None:
|
||||
existing_query = existing_query.filter(KbGroup.department_id.is_(None))
|
||||
else:
|
||||
existing_query = existing_query.filter(KbGroup.department_id == department_id)
|
||||
if existing_query.first():
|
||||
raise ValidationError('知识库分组已存在')
|
||||
current_user = get_current_user()
|
||||
group = KbGroup(
|
||||
name=name,
|
||||
description=description,
|
||||
department_id=department_id,
|
||||
created_by_id=getattr(current_user, 'id', None),
|
||||
updated_by_id=getattr(current_user, 'id', None),
|
||||
)
|
||||
db.session.add(group)
|
||||
db.session.commit()
|
||||
return jsonify(serialize_group(group, 0)), 201
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/groups/<int:group_id>', methods=['PATCH'])
|
||||
@require_admin
|
||||
def update_group(group_id: int):
|
||||
group = db.session.get(KbGroup, group_id)
|
||||
if not group or not group.is_active:
|
||||
raise NotFoundError('知识库分组不存在')
|
||||
data = request.get_json(silent=True) or {}
|
||||
name = str(data.get('name') or group.name).strip()
|
||||
description = data.get('description')
|
||||
department_id = data.get('department_id', group.department_id)
|
||||
if not name:
|
||||
raise ValidationError('name is required')
|
||||
existing_query = db.session.query(KbGroup).filter(
|
||||
KbGroup.id != group.id,
|
||||
KbGroup.name == name,
|
||||
KbGroup.is_active.is_(True),
|
||||
)
|
||||
if department_id is None:
|
||||
existing_query = existing_query.filter(KbGroup.department_id.is_(None))
|
||||
else:
|
||||
existing_query = existing_query.filter(KbGroup.department_id == department_id)
|
||||
if existing_query.first():
|
||||
raise ValidationError('知识库分组已存在')
|
||||
current_user = get_current_user()
|
||||
group.name = name
|
||||
group.description = str(description).strip() or None if description is not None else None
|
||||
group.department_id = department_id
|
||||
group.updated_by_id = getattr(current_user, 'id', None)
|
||||
db.session.commit()
|
||||
document_count = db.session.query(func.count(KbDocument.id)).filter(
|
||||
KbDocument.group_id == group.id,
|
||||
KbDocument.is_deleted.is_(False),
|
||||
).scalar()
|
||||
return jsonify(serialize_group(group, document_count))
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/groups/<int:group_id>', methods=['DELETE'])
|
||||
@require_admin
|
||||
def delete_group(group_id: int):
|
||||
group = db.session.get(KbGroup, group_id)
|
||||
if not group or not group.is_active:
|
||||
raise NotFoundError('知识库分组不存在')
|
||||
current_user = get_current_user()
|
||||
group.is_active = False
|
||||
group.updated_by_id = getattr(current_user, 'id', None)
|
||||
cancel_active_kb_jobs_for_group(group.id, '知识库分组已删除,后台任务已取消')
|
||||
db.session.commit()
|
||||
return jsonify({'ok': True, 'id': group_id})
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/groups/<int:group_id>/files', methods=['GET'])
|
||||
def list_group_files(group_id: int):
|
||||
require_user()
|
||||
group = run_db_read('get_group_for_files', lambda: db.session.get(KbGroup, group_id))
|
||||
if not group or not group.is_active:
|
||||
raise NotFoundError('Knowledge base group not found')
|
||||
documents = run_db_read(
|
||||
'list_group_files',
|
||||
lambda: db.session.query(KbDocument)
|
||||
.options(joinedload(KbDocument.versions))
|
||||
.filter(KbDocument.group_id == group_id, KbDocument.is_deleted.is_(False))
|
||||
.order_by(KbDocument.updated_at.desc(), KbDocument.id.desc())
|
||||
.all(),
|
||||
)
|
||||
return jsonify([serialize_document(doc) for doc in documents])
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/groups/<int:group_id>/files', methods=['POST'])
|
||||
def create_group_file(group_id: int):
|
||||
current_user = require_user()
|
||||
path_upload_service.require_active_group(group_id)
|
||||
data = request.get_json(silent=True) or {}
|
||||
title = str(data.get('title') or '').strip()
|
||||
description = str(data.get('description') or '').strip() or None
|
||||
status = str(data.get('status') or 'draft').strip() or 'draft'
|
||||
if not title:
|
||||
raise ValidationError('title is required')
|
||||
existing = (
|
||||
db.session.query(KbDocument)
|
||||
.options(joinedload(KbDocument.versions))
|
||||
.filter(KbDocument.group_id == group_id, KbDocument.title == title)
|
||||
.first()
|
||||
)
|
||||
if existing and not existing.is_deleted:
|
||||
raise ValidationError('当前分组下已存在同名文档')
|
||||
if existing and existing.is_deleted:
|
||||
existing.is_deleted = False
|
||||
existing.description = description
|
||||
existing.status = status
|
||||
existing.updated_by_id = getattr(current_user, 'id', None)
|
||||
db.session.commit()
|
||||
return jsonify(serialize_document(existing)), 201
|
||||
document = KbDocument(
|
||||
group_id=group_id,
|
||||
title=title,
|
||||
description=description,
|
||||
status=status,
|
||||
source_type='manual',
|
||||
created_by_id=getattr(current_user, 'id', None),
|
||||
updated_by_id=getattr(current_user, 'id', None),
|
||||
)
|
||||
db.session.add(document)
|
||||
db.session.commit()
|
||||
return jsonify(serialize_document(document)), 201
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/groups/<int:group_id>/path-upload-jobs', methods=['POST'])
|
||||
def create_path_upload_job(group_id: int):
|
||||
current_user = require_user()
|
||||
path_upload_service.require_active_group(group_id)
|
||||
job, reused = path_upload_service.create_path_upload_job(
|
||||
group_id,
|
||||
request.get_json(silent=True) or {},
|
||||
user_id=getattr(current_user, 'id', None),
|
||||
)
|
||||
db.session.commit()
|
||||
payload = serialize_job(job)
|
||||
if reused:
|
||||
payload['reused_existing'] = True
|
||||
payload['message'] = payload.get('message') or '检测到未完成的路径上传任务,已自动续传'
|
||||
return jsonify(payload)
|
||||
return jsonify(payload), 201
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/path-upload-jobs/<int:job_id>/files', methods=['POST'])
|
||||
def upload_path_job_file(job_id: int):
|
||||
current_user = require_user()
|
||||
job = path_upload_service.require_path_upload_job(job_id)
|
||||
try:
|
||||
job = path_upload_service.upload_path_job_file(
|
||||
job,
|
||||
file_storage=request.files.get('file'),
|
||||
relative_path_raw=request.form.get('relative_path'),
|
||||
user_id=getattr(current_user, 'id', None),
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise ValidationError(str(exc)) from exc
|
||||
db.session.commit()
|
||||
return jsonify(serialize_job(job)), 201
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/path-upload-jobs/<int:job_id>/files/fail', methods=['POST'])
|
||||
def mark_path_job_file_failed(job_id: int):
|
||||
require_user()
|
||||
job = path_upload_service.require_path_upload_job(job_id)
|
||||
data = request.get_json(silent=True) or {}
|
||||
original_name = str(data.get('original_name') or '').strip() or None
|
||||
relative_path_raw = str(data.get('relative_path') or '').strip()
|
||||
error_message = str(data.get('error') or '路径文件上传失败').strip() or '路径文件上传失败'
|
||||
try:
|
||||
job = path_upload_service.mark_path_job_file_failed(
|
||||
job,
|
||||
relative_path_raw=relative_path_raw,
|
||||
original_name=original_name,
|
||||
error_message=error_message,
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise ValidationError(str(exc)) from exc
|
||||
db.session.commit()
|
||||
return jsonify(serialize_job(job))
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/path-upload-jobs/<int:job_id>/finalize', methods=['POST'])
|
||||
def finalize_path_upload_job(job_id: int):
|
||||
current_user = require_user()
|
||||
job = path_upload_service.require_path_upload_job(job_id)
|
||||
job, status_code = path_upload_service.finalize_path_upload_job(
|
||||
job,
|
||||
user_id=getattr(current_user, 'id', None),
|
||||
)
|
||||
db.session.commit()
|
||||
refreshed = db.session.get(KbJob, job.id)
|
||||
response_payload = serialize_job(refreshed or job)
|
||||
if status_code == 202:
|
||||
response_payload['queue_result'] = 'inline_per_file'
|
||||
response_payload['accepted'] = True
|
||||
return jsonify(response_payload), status_code
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/path-upload-jobs/<int:job_id>/files', methods=['DELETE'])
|
||||
def delete_path_job_file(job_id: int):
|
||||
current_user = require_user()
|
||||
job = path_upload_service.require_path_upload_job(job_id)
|
||||
relative_path_raw = str(request.args.get('relative_path') or '').strip()
|
||||
if not relative_path_raw:
|
||||
raise ValidationError('relative_path is required')
|
||||
try:
|
||||
job, document_deleted, relative_path = path_upload_service.delete_path_job_file(
|
||||
job,
|
||||
relative_path_raw=relative_path_raw,
|
||||
user_id=getattr(current_user, 'id', None),
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise ValidationError(str(exc)) from exc
|
||||
db.session.commit()
|
||||
return jsonify({
|
||||
'ok': True,
|
||||
'job': serialize_job(job),
|
||||
'document_deleted': document_deleted,
|
||||
'relative_path': relative_path,
|
||||
})
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/path-upload-jobs/<int:job_id>/retry-failed', methods=['POST'])
|
||||
def retry_failed_path_upload_job(job_id: int):
|
||||
current_user = require_user()
|
||||
source_job = path_upload_service.require_path_upload_job(job_id)
|
||||
data = request.get_json(silent=True) or {}
|
||||
requested_paths = data.get('relative_paths') or []
|
||||
if not isinstance(requested_paths, list):
|
||||
requested_paths = []
|
||||
retry_job = path_upload_service.retry_failed_path_upload_job(
|
||||
source_job,
|
||||
relative_paths=requested_paths,
|
||||
user_id=getattr(current_user, 'id', None),
|
||||
)
|
||||
db.session.commit()
|
||||
refreshed = db.session.get(KbJob, retry_job.id)
|
||||
return jsonify(serialize_job(refreshed or retry_job)), 201
|
||||
@@ -0,0 +1,97 @@
|
||||
"""
|
||||
backend/app/api/kb/jobs.py
|
||||
|
||||
用途:知识库后台任务 API(列表、手动触发);序列化/取消 helper 来自 services/kb/job_lifecycle。
|
||||
依赖:kb.blueprint、kb.common、app.jobs、services/kb/job_lifecycle。
|
||||
逻辑:注册 /jobs 路由。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import jsonify
|
||||
|
||||
from app import db
|
||||
from app.api.kb.blueprint import knowledge_base_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.jobs import enqueue_kb_job
|
||||
from app.models import KbDocumentVersion, KbJob
|
||||
from app.services.kb.job_lifecycle import serialize_job
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/jobs', methods=['GET'])
|
||||
def list_jobs():
|
||||
"""
|
||||
返回最近 50 条 KbJob(登录用户可见)。
|
||||
核心逻辑:只读查询,经 run_db_read 处理瞬态 DB 错误。
|
||||
"""
|
||||
from app.api.kb.common import require_user, run_db_read
|
||||
|
||||
require_user()
|
||||
jobs = run_db_read(
|
||||
'list_jobs',
|
||||
lambda: db.session.query(KbJob)
|
||||
.order_by(KbJob.created_at.desc(), KbJob.id.desc())
|
||||
.limit(50)
|
||||
.all(),
|
||||
)
|
||||
return jsonify([serialize_job(job) for job in jobs])
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/jobs/<int:job_id>/run', methods=['POST'])
|
||||
@require_admin
|
||||
def run_job(job_id: int):
|
||||
"""
|
||||
管理员手动将 clean/sync_dify 任务重新提交后台执行。
|
||||
核心逻辑:重置 queued 状态后 enqueue_kb_job;已在队列中则 202 返回 already_queued。
|
||||
"""
|
||||
job = db.session.get(KbJob, job_id)
|
||||
if not job:
|
||||
raise NotFoundError('任务不存在')
|
||||
|
||||
if job.job_type not in ('clean', 'sync_dify'):
|
||||
raise ValidationError('当前仅支持手动执行 clean 或 sync_dify 任务')
|
||||
|
||||
if job.status in ('queued', 'running'):
|
||||
refreshed = db.session.get(KbJob, job_id)
|
||||
payload = serialize_job(refreshed) if refreshed else {'id': job_id}
|
||||
payload['accepted'] = True
|
||||
payload['queue_result'] = 'already_queued'
|
||||
payload['run_result'] = '任务已在后台处理中'
|
||||
return jsonify(payload), 202
|
||||
|
||||
version = db.session.get(KbDocumentVersion, job.document_version_id) if job.document_version_id else None
|
||||
|
||||
if job.job_type == 'clean':
|
||||
if not version:
|
||||
raise NotFoundError('关联文档版本不存在')
|
||||
job.status = 'queued'
|
||||
job.progress = 0
|
||||
job.started_at = None
|
||||
job.finished_at = None
|
||||
job.error_message = None
|
||||
job.message = '等待清洗任务执行'
|
||||
version.status = 'uploaded'
|
||||
version.error_message = None
|
||||
if version.document:
|
||||
version.document.status = 'uploaded'
|
||||
else:
|
||||
if not version:
|
||||
raise NotFoundError('关联文档版本不存在')
|
||||
job.status = 'queued'
|
||||
job.progress = 0
|
||||
job.started_at = None
|
||||
job.finished_at = None
|
||||
job.error_message = None
|
||||
job.message = '等待同步到 Dify'
|
||||
if version.status in ('failed', 'ready', 'synced'):
|
||||
version.error_message = None
|
||||
|
||||
db.session.commit()
|
||||
|
||||
_enqueued, queue_result = enqueue_kb_job(job.id)
|
||||
refreshed = db.session.get(KbJob, job_id)
|
||||
payload = serialize_job(refreshed) if refreshed else {'id': job_id}
|
||||
payload['accepted'] = True
|
||||
payload['queue_result'] = queue_result
|
||||
payload['run_result'] = '任务已提交后台异步执行'
|
||||
return jsonify(payload), 202
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,9 +1,10 @@
|
||||
"""
|
||||
backend/app/api/schedule/__init__.py
|
||||
|
||||
用途:排程管理 Blueprint 入口(自 schedule_admin.py 收敛)。
|
||||
逻辑:Wave 1 前 re-export 旧模块 blueprint。
|
||||
用途:排程管理 Blueprint 入口(Wave 3:自 schedule_admin 单体迁入 _legacy)。
|
||||
依赖:schedule/_legacy.py(路由实现)、schedule/* services。
|
||||
逻辑:register_blueprints 从本包 import schedule_admin_bp;后续从 _legacy 拆 tasks.py / runs.py。
|
||||
"""
|
||||
from app.api.schedule_admin import schedule_admin_bp # noqa: F401
|
||||
from app.api.schedule._legacy import schedule_admin_bp
|
||||
|
||||
__all__ = ['schedule_admin_bp']
|
||||
@@ -0,0 +1,529 @@
|
||||
"""
|
||||
backend/app/api/schedule/_legacy.py
|
||||
|
||||
用途:排程任务与运行记录管理 API(admin 域,Wave 3 迁包源文件)。
|
||||
依赖:app.core.decorators、app.core.auth.jwt、app.core.errors、schedule/* services。
|
||||
逻辑:管理员 CRUD ScheduleTask、触发运行、导出;后续拆至 schedule/tasks.py、runs.py。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
import threading
|
||||
from datetime import datetime
|
||||
from flask import Blueprint, current_app, jsonify, request, send_file
|
||||
from flask import Response
|
||||
from io import BytesIO
|
||||
import json
|
||||
from app.core.decorators import require_admin
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, ScheduleTaskConfig
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.services.schedule.query_service import get_run, list_runs, list_tasks, serialize_run, serialize_task
|
||||
from app.services.schedule.scheduler_service import create_task, run_task_now, update_task, _generate_run_no, _generate_test_run_no, _notify_schedule_run_wecom
|
||||
from app.services.schedule.sql_config import get_schedule_sql_config_by_task_id, upsert_schedule_task_config, _build_fetch_sql
|
||||
from app.services.schedule.srm_service import _fetch_records
|
||||
from app.core.errors import (
|
||||
AppError,
|
||||
ConflictError,
|
||||
ForbiddenError,
|
||||
NotFoundError,
|
||||
ServiceUnavailableError,
|
||||
UnauthorizedError,
|
||||
ValidationError,
|
||||
raise_for_status,
|
||||
)
|
||||
schedule_admin_bp = Blueprint('schedule_admin', __name__)
|
||||
|
||||
def _serialize_task_for_export(task: ScheduleTask, cfg_model: ScheduleTaskConfig | None) -> dict:
|
||||
payload = serialize_task(task)
|
||||
payload['config'] = _serialize_task_config(cfg_model) if cfg_model else None
|
||||
return payload
|
||||
|
||||
def _serialize_task_config(cfg_model: ScheduleTaskConfig) -> dict:
|
||||
return {'row_id_key': cfg_model.row_id_key or 'id', 'log_prefix': cfg_model.log_prefix or '', 'base_fetch_sql': cfg_model.base_fetch_sql or '', 'fetch_where_conditions': cfg_model.fetch_where_conditions or '', 'fetch_order_by': cfg_model.fetch_order_by or '', 'writeback_sql': cfg_model.writeback_sql or '', 'detail_sql': cfg_model.detail_sql or '', 'alias_order': cfg_model.alias_order or [], 'detail_alias_order': cfg_model.detail_alias_order or [], 'header_labels': cfg_model.header_labels or {}, 'data_source': {'db_type': cfg_model.ds_db_type or 'sqlserver', 'host': cfg_model.ds_host or '', 'port': cfg_model.ds_port or '', 'database': cfg_model.ds_database or '', 'username': cfg_model.ds_username or '', 'password': cfg_model.ds_password or '', 'driver': cfg_model.ds_driver or '', 'encrypt': cfg_model.ds_encrypt or '', 'trust_cert': cfg_model.ds_trust_cert or ''}, 'external_api': {'url': cfg_model.api_url or '', 'method': cfg_model.api_method or 'POST', 'headers': cfg_model.api_headers or {}, 'body_template': cfg_model.api_body_template or ''}, 'dify_system_prompt': cfg_model.dify_system_prompt or ''}
|
||||
|
||||
@schedule_admin_bp.route('/schedule-config/<int:task_id>', methods=['GET'])
|
||||
@require_admin
|
||||
def get_schedule_task_config(task_id: int):
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
|
||||
if not cfg_model:
|
||||
return jsonify({'data_source_type': task.data_source_type, 'config': None})
|
||||
return jsonify({'data_source_type': task.data_source_type, 'config': _serialize_task_config(cfg_model)})
|
||||
|
||||
@schedule_admin_bp.route('/schedule-config/<int:task_id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_schedule_task_config(task_id: int):
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
data = request.get_json(silent=True) or {}
|
||||
try:
|
||||
if 'data_source_type' in data:
|
||||
task.data_source_type = str(data['data_source_type'])
|
||||
db.session.commit()
|
||||
config_data = data.get('config', data)
|
||||
cfg = upsert_schedule_task_config(task_id, config_data)
|
||||
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
|
||||
return jsonify({'data_source_type': task.data_source_type, 'config': _serialize_task_config(cfg_model) if cfg_model else None})
|
||||
except Exception as e:
|
||||
db.session.rollback()
|
||||
raise ValidationError(str(e))
|
||||
|
||||
@schedule_admin_bp.route('/schedule-config/<int:task_id>/test-sql', methods=['POST'])
|
||||
@require_admin
|
||||
def test_schedule_sql(task_id: int):
|
||||
cfg = get_schedule_sql_config_by_task_id(task_id)
|
||||
if not cfg:
|
||||
raise NotFoundError(f'Config for task {task_id} not found')
|
||||
data = request.get_json(silent=True) or {}
|
||||
custom_where = str(data.get('fetch_where_conditions') or cfg.fetch_where_conditions).strip()
|
||||
custom_order_by = str(data.get('fetch_order_by') or cfg.fetch_order_by).strip()
|
||||
limit = min(int(data.get('limit') or 10), 100)
|
||||
base = cfg.base_fetch_sql or cfg.fetch_sql
|
||||
if cfg.base_fetch_sql:
|
||||
sql = _build_fetch_sql(base, custom_where, custom_order_by)
|
||||
else:
|
||||
sql = base
|
||||
try:
|
||||
from app.services.schedule import _build_srm_conn_str
|
||||
import decimal, datetime
|
||||
if cfg.data_source and (not cfg.data_source.is_empty()):
|
||||
conn_str = cfg.data_source.build_connection_string()
|
||||
else:
|
||||
conn_str = _build_srm_conn_str()
|
||||
rows = _fetch_records(conn_str, sql)
|
||||
|
||||
def _safe(v):
|
||||
if isinstance(v, decimal.Decimal):
|
||||
return float(v)
|
||||
if isinstance(v, (datetime.date, datetime.datetime)):
|
||||
return v.isoformat()
|
||||
if isinstance(v, datetime.timedelta):
|
||||
return str(v)
|
||||
return v
|
||||
result_rows = [{k: _safe(v) for k, v in r.items()} for r in rows[:limit]]
|
||||
return jsonify({'total': len(rows), 'showing': len(result_rows), 'limit': limit, 'sql': sql, 'columns': list(result_rows[0].keys()) if result_rows else [], 'rows': result_rows})
|
||||
except Exception as e:
|
||||
raise AppError(code='SYSTEM.HTTP_ERROR', message=str(e), http_status=400, details={'sql': sql})
|
||||
|
||||
@schedule_admin_bp.route('/schedule-config/<int:task_id>/test-run', methods=['POST'])
|
||||
@require_admin
|
||||
def test_schedule_run(task_id: int):
|
||||
import time as _time
|
||||
from app.services.schedule.excel_service import export_schedule_result_excel
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
cfg = get_schedule_sql_config_by_task_id(task_id)
|
||||
if not cfg:
|
||||
raise NotFoundError(f'Config for task {task_id} not found')
|
||||
data = request.get_json(silent=True) or {}
|
||||
custom_where = str(data.get('fetch_where_conditions') or cfg.fetch_where_conditions).strip()
|
||||
custom_order_by = str(data.get('fetch_order_by') or cfg.fetch_order_by).strip()
|
||||
limit = min(int(data.get('limit') or 3), 10)
|
||||
raw_kb_sync = data.get('kb_sync_enabled', False)
|
||||
if isinstance(raw_kb_sync, str):
|
||||
test_kb_sync_enabled = raw_kb_sync.strip().lower() in ('1', 'true', 'yes', 'on')
|
||||
else:
|
||||
test_kb_sync_enabled = bool(raw_kb_sync)
|
||||
base = cfg.base_fetch_sql or cfg.fetch_sql
|
||||
if cfg.base_fetch_sql:
|
||||
test_sql = _build_fetch_sql(base, custom_where, custom_order_by)
|
||||
else:
|
||||
test_sql = base
|
||||
from app.services.schedule import _build_srm_conn_str, _resolve_dify_agent, _resolve_schedule_user
|
||||
from app.services.schedule.srm_service import _fetch_records, _run_check_job_loop, _build_record_text, _execute_writeback
|
||||
if cfg.data_source and (not cfg.data_source.is_empty()):
|
||||
conn_str = cfg.data_source.build_connection_string()
|
||||
else:
|
||||
conn_str = _build_srm_conn_str()
|
||||
agent = _resolve_dify_agent(task) if task else None
|
||||
user = _resolve_schedule_user(task) if task else 'test_user'
|
||||
wait_seconds = task.wait_seconds if task else 120
|
||||
dify_agent_id = task.dify_agent_id if task else None
|
||||
run = ScheduleRun(run_no=_generate_test_run_no(), schedule_task_id=task_id, trigger_type='test', triggered_by_user_id=getattr(get_current_user(), 'id', None), started_at=datetime.utcnow(), status='running')
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
from app.services.schedule.dify_snapshot import capture_dify_execution_snapshot
|
||||
capture_dify_execution_snapshot(run, task)
|
||||
db.session.commit()
|
||||
if not cfg.fetch_sql:
|
||||
run.status = 'success'
|
||||
run.finished_at = datetime.utcnow()
|
||||
run.error_message = '无抓取SQL,跳过外部系统数据抓取'
|
||||
try:
|
||||
if task.notify_enabled:
|
||||
_notify_schedule_run_wecom(task, run)
|
||||
except Exception as wecom_exc:
|
||||
current_app.logger.error('[schedule-test-run] wecom notify failed: %s', wecom_exc)
|
||||
db.session.commit()
|
||||
return jsonify({'run_no': run.run_no, 'run_id': run.id, 'sql': '', 'limit': 0, 'total_count': 0, 'success_count': 0, 'failed_count': 0, 'skipped_count': 0, 'details': [], 'errors': [], 'step_logs': [{'step': 'no_fetch_sql', 'status': 'skipped', 'detail': '无抓取SQL,跳过外部系统数据抓取'}], 'dify_agent_id': dify_agent_id})
|
||||
|
||||
def _test_fetch_fn(conn_str_arg):
|
||||
return _fetch_records(conn_str_arg, test_sql)
|
||||
|
||||
def _test_writeback_fn(conn_str_arg, *, row_id, run_no, dify_result, dify_message):
|
||||
_execute_writeback(conn_str_arg, cfg.writeback_sql, (run_no, dify_result, dify_message, str(row_id)))
|
||||
test_pre_dify = None
|
||||
test_build_record = None
|
||||
if cfg.detail_sql:
|
||||
|
||||
def _test_pre_dify(conn_str_arg, item, row_id_value):
|
||||
try:
|
||||
detail_rows = _fetch_records(conn_str_arg, cfg.detail_sql, params=(str(row_id_value),))
|
||||
except Exception as detail_exc:
|
||||
return {'dify_result': '人工判定', 'dify_message': f'查询成分明细失败:{detail_exc}', 'writeback_srm': False, 'writeback_err': str(detail_exc)}
|
||||
detail_lines = []
|
||||
for dr in detail_rows:
|
||||
parts = [f"{cfg.header_labels.get(dk, dk)}: {dr.get(dk, '')}" for dk in cfg.detail_alias_order]
|
||||
detail_lines.append(', '.join(parts))
|
||||
item['detail_text'] = '; '.join(detail_lines) if detail_lines else ''
|
||||
item['_detail_rows'] = detail_rows
|
||||
return None
|
||||
test_pre_dify = _test_pre_dify
|
||||
|
||||
def _test_build_with_detail(conn_str_arg, item, row_id_value):
|
||||
detail_rows = item.get('_detail_rows', [])
|
||||
text = _build_record_text(item, cfg.alias_order, cfg.header_labels, detail_rows, cfg.detail_alias_order)
|
||||
return (text, item.get('attachment'))
|
||||
test_build_record = _test_build_with_detail
|
||||
else:
|
||||
|
||||
def _test_build_simple(conn_str_arg, item, row_id_value):
|
||||
text = _build_record_text(item, cfg.alias_order, cfg.header_labels)
|
||||
return (text, item.get('attachment'))
|
||||
test_build_record = _test_build_simple
|
||||
start_ts = _time.time()
|
||||
try:
|
||||
total_count, success_count, failed_count, skipped_count, details, errors, step_logs = _run_check_job_loop(conn_str=conn_str, run_no=run.run_no, agent=agent, user=user, wait_seconds=wait_seconds, run_id=run.id, fetch_fn=_test_fetch_fn, build_record_fn=test_build_record, writeback_fn=_test_writeback_fn, writeback_sql=cfg.writeback_sql, row_id_key=cfg.row_id_key, log_prefix=cfg.log_prefix, fetch_sql=test_sql, max_rows=limit, pre_dify_fn=test_pre_dify, dify_system_prompt=cfg.dify_system_prompt)
|
||||
duration_ms = int((_time.time() - start_ts) * 1000)
|
||||
if total_count == 0 and (not errors):
|
||||
status = 'success'
|
||||
elif failed_count == 0:
|
||||
status = 'success'
|
||||
elif success_count == 0:
|
||||
status = 'failed'
|
||||
else:
|
||||
status = 'partial_failed'
|
||||
header_order = cfg.alias_order if cfg.alias_order else None
|
||||
header_labels = cfg.header_labels if cfg.header_labels else None
|
||||
detail_alias_order = cfg.detail_alias_order or []
|
||||
try:
|
||||
file_data, file_name, file_size = export_schedule_result_excel(run_no=run.run_no, summary={'status': status, 'total_count': total_count, 'success_count': success_count, 'failed_count': failed_count, 'duration_ms': duration_ms}, details=details, header_order=header_order, header_labels=header_labels, detail_alias_order=detail_alias_order)
|
||||
except Exception as excel_exc:
|
||||
current_app.logger.error('[schedule-test-run] excel export failed: %s', excel_exc, exc_info=True)
|
||||
file_data, file_name, file_size = (None, None, 0)
|
||||
run.finished_at = datetime.utcnow()
|
||||
run.duration_ms = duration_ms
|
||||
run.status = status
|
||||
run.total_count = total_count
|
||||
run.success_count = success_count
|
||||
run.failed_count = failed_count
|
||||
run.skipped_count = skipped_count
|
||||
run.step_logs = step_logs if step_logs else None
|
||||
run.error_message = '; '.join(errors[:3]) if errors else None
|
||||
run.excel_file_data = file_data
|
||||
run.excel_file_name = file_name
|
||||
run.excel_file_size = file_size or 0
|
||||
db.session.commit()
|
||||
if test_kb_sync_enabled:
|
||||
try:
|
||||
from app.services.schedule.kb_sync import sync_schedule_run_excel_to_kb
|
||||
|
||||
db.session.refresh(task)
|
||||
db.session.refresh(run)
|
||||
sync_schedule_run_excel_to_kb(task, run, enabled=True, process_inline=True)
|
||||
db.session.refresh(run)
|
||||
except Exception as kb_exc:
|
||||
db.session.rollback()
|
||||
db.session.refresh(run)
|
||||
current_app.logger.error('[schedule-test-run] kb sync failed: %s', kb_exc, exc_info=True)
|
||||
run.kb_sync_status = 'failed'
|
||||
run.kb_group_id = getattr(task, 'kb_group_id', None)
|
||||
run.kb_sync_error = str(kb_exc)
|
||||
db.session.commit()
|
||||
try:
|
||||
if task.notify_enabled:
|
||||
_notify_schedule_run_wecom(task, run)
|
||||
except Exception as wecom_exc:
|
||||
current_app.logger.error('[schedule-test-run] wecom notify failed: %s', wecom_exc)
|
||||
import decimal, datetime as dt
|
||||
|
||||
def _safe(v):
|
||||
if isinstance(v, decimal.Decimal):
|
||||
return float(v)
|
||||
if isinstance(v, (dt.date, dt.datetime)):
|
||||
return v.isoformat()
|
||||
if isinstance(v, dt.timedelta):
|
||||
return str(v)
|
||||
return v
|
||||
safe_details = []
|
||||
for item in details:
|
||||
safe_item = {k: _safe(v) for k, v in item.items()}
|
||||
safe_details.append(safe_item)
|
||||
return jsonify({'run_no': run.run_no, 'run_id': run.id, 'sql': test_sql, 'limit': limit, 'total_count': total_count, 'success_count': success_count, 'failed_count': failed_count, 'skipped_count': skipped_count, 'details': safe_details, 'errors': errors, 'step_logs': step_logs, 'dify_agent_id': dify_agent_id, 'dify_execution_snapshot': run.dify_execution_snapshot, 'kb_sync_status': run.kb_sync_status, 'kb_sync_error': run.kb_sync_error, 'kb_document_id': run.kb_document_id})
|
||||
except Exception as e:
|
||||
db.session.rollback()
|
||||
run = db.session.get(ScheduleRun, run.id)
|
||||
duration_ms = int((_time.time() - start_ts) * 1000)
|
||||
run.finished_at = datetime.utcnow()
|
||||
run.duration_ms = duration_ms
|
||||
run.status = 'failed'
|
||||
run.error_message = str(e)
|
||||
db.session.commit()
|
||||
import traceback
|
||||
raise AppError(code='SYSTEM.HTTP_ERROR', message=str(e), http_status=400, details={'sql': test_sql, 'traceback': traceback.format_exc()})
|
||||
|
||||
@schedule_admin_bp.route('/schedules', methods=['GET'])
|
||||
@require_admin
|
||||
def get_schedules():
|
||||
return jsonify(list_tasks())
|
||||
|
||||
@schedule_admin_bp.route('/schedules/<int:task_id>/export', methods=['GET'])
|
||||
@require_admin
|
||||
def export_schedule(task_id: int):
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
|
||||
payload = {'schema_version': 1, 'exported_at': datetime.utcnow().isoformat(), 'schedules': [_serialize_task_for_export(task, cfg_model)]}
|
||||
body = json.dumps(payload, ensure_ascii=False, indent=2)
|
||||
filename = f"{task.schedule_no or f'schedule_{task.id}'}_export_{datetime.utcnow().strftime('%Y%m%d_%H%M%S')}.json"
|
||||
return Response(body, mimetype='application/json; charset=utf-8', headers={'Content-Disposition': f'attachment; filename="{filename}"'})
|
||||
|
||||
@schedule_admin_bp.route('/schedules/import', methods=['POST'])
|
||||
@require_admin
|
||||
def import_schedules():
|
||||
data = request.get_json(silent=True) or {}
|
||||
schedules = data.get('schedules')
|
||||
if not isinstance(schedules, list):
|
||||
raise ValidationError('Invalid import file: schedules missing')
|
||||
user = get_current_user()
|
||||
imported = 0
|
||||
skipped = 0
|
||||
errors: list[str] = []
|
||||
for item in schedules:
|
||||
if not isinstance(item, dict):
|
||||
skipped += 1
|
||||
continue
|
||||
try:
|
||||
name = str(item.get('name') or '').strip()
|
||||
cron_expr = str(item.get('cron_expr') or '').strip()
|
||||
owner_user_id = int(item.get('owner_user_id'))
|
||||
if not name or not cron_expr:
|
||||
raise ValueError('name or cron_expr missing')
|
||||
existing = None
|
||||
schedule_no = str(item.get('schedule_no') or '').strip()
|
||||
if schedule_no:
|
||||
existing = db.session.query(ScheduleTask).filter_by(schedule_no=schedule_no).first()
|
||||
task_payload = {'name': name, 'schedule_type': str(item.get('schedule_type') or 'platform_app'), 'owner_user_id': owner_user_id, 'cron_expr': cron_expr, 'schedule_timezone': item.get('schedule_timezone'), 'wait_seconds': int(item.get('wait_seconds') or 0), 'dify_agent_id': item.get('dify_agent_id'), 'platform_api_path': item.get('platform_api_path'), 'notify_user_ids_json': item.get('notify_user_ids_json') if isinstance(item.get('notify_user_ids_json'), list) else [], 'notify_enabled': bool(item.get('notify_enabled', True)), 'enabled': bool(item.get('enabled', True)), 'data_source_type': str(item.get('data_source_type') or 'database'), 'kb_sync_enabled': bool(item.get('kb_sync_enabled', False)), 'kb_group_id': item.get('kb_group_id')}
|
||||
cfg = item.get('config') if isinstance(item.get('config'), dict) else None
|
||||
if existing:
|
||||
update_task(existing, payload=task_payload, actor_id=getattr(user, 'id', None))
|
||||
existing.data_source_type = task_payload['data_source_type']
|
||||
if cfg:
|
||||
upsert_schedule_task_config(existing.id, cfg)
|
||||
else:
|
||||
task = create_task(name=name, schedule_type=task_payload['schedule_type'], owner_user_id=owner_user_id, cron_expr=cron_expr, schedule_timezone=task_payload['schedule_timezone'], wait_seconds=task_payload['wait_seconds'], dify_agent_id=task_payload['dify_agent_id'], platform_api_path=task_payload['platform_api_path'], notify_user_ids_json=task_payload['notify_user_ids_json'], notify_enabled=task_payload['notify_enabled'], enabled=task_payload['enabled'], actor_id=getattr(user, 'id', None))
|
||||
task.data_source_type = task_payload['data_source_type']
|
||||
task.kb_sync_enabled = task_payload['kb_sync_enabled']
|
||||
task.kb_group_id = int(task_payload['kb_group_id']) if task_payload.get('kb_group_id') not in (None, '', 0, '0') else None
|
||||
db.session.commit()
|
||||
if cfg:
|
||||
upsert_schedule_task_config(task.id, cfg)
|
||||
imported += 1
|
||||
except Exception as exc:
|
||||
errors.append(str(exc))
|
||||
skipped += 1
|
||||
db.session.commit()
|
||||
return jsonify({'ok': True, 'imported': imported, 'skipped': skipped, 'errors': errors[:20]})
|
||||
|
||||
@schedule_admin_bp.route('/schedules', methods=['POST'])
|
||||
@require_admin
|
||||
def post_schedule():
|
||||
data = request.get_json(silent=True) or {}
|
||||
user = get_current_user()
|
||||
data_source_type = str(data.get('data_source_type') or 'database')
|
||||
task = create_task(name=str(data.get('name') or '').strip(), schedule_type='platform_app', owner_user_id=int(data.get('owner_user_id')), cron_expr=str(data.get('cron_expr') or '').strip(), schedule_timezone=data.get('schedule_timezone'), wait_seconds=int(data.get('wait_seconds') or 0), dify_agent_id=int(data.get('dify_agent_id')) if data.get('dify_agent_id') is not None else None, platform_api_path=str(data.get('platform_api_path') or '').strip() or None, notify_user_ids_json=data.get('notify_user_ids_json') if isinstance(data.get('notify_user_ids_json'), list) else [], notify_enabled=bool(data.get('notify_enabled', True)), enabled=bool(data.get('enabled', True)), actor_id=getattr(user, 'id', None))
|
||||
task.data_source_type = data_source_type
|
||||
task.kb_sync_enabled = bool(data.get('kb_sync_enabled', False))
|
||||
raw_kb_group_id = data.get('kb_group_id')
|
||||
task.kb_group_id = int(raw_kb_group_id) if raw_kb_group_id not in (None, '', 0, '0') else None
|
||||
if data_source_type == 'faq_hot_aggregate':
|
||||
task.platform_api_path = 'faq-aggregate-hot'
|
||||
else:
|
||||
task.platform_api_path = f'/{task.id}'
|
||||
db.session.commit()
|
||||
db.session.refresh(task)
|
||||
config_data = data.get('config')
|
||||
if config_data and data_source_type != 'faq_hot_aggregate':
|
||||
upsert_schedule_task_config(task.id, config_data)
|
||||
if not task.dify_agent_id:
|
||||
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task.id).first()
|
||||
if cfg_model and cfg_model.dify_system_prompt:
|
||||
cfg_model.dify_system_prompt = None
|
||||
db.session.commit()
|
||||
return (jsonify(serialize_task(task)), 201)
|
||||
|
||||
@schedule_admin_bp.route('/schedules/<int:task_id>', methods=['GET'])
|
||||
@require_admin
|
||||
def get_schedule(task_id: int):
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
return jsonify(serialize_task(task))
|
||||
|
||||
@schedule_admin_bp.route('/schedules/<int:task_id>', methods=['PATCH'])
|
||||
@require_admin
|
||||
def patch_schedule(task_id: int):
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
data = request.get_json(silent=True) or {}
|
||||
user = get_current_user()
|
||||
if 'data_source_type' in data:
|
||||
task.data_source_type = str(data['data_source_type'])
|
||||
db.session.commit()
|
||||
config_data = data.get('config')
|
||||
if config_data:
|
||||
upsert_schedule_task_config(task_id, config_data)
|
||||
task = update_task(task, payload=data, actor_id=getattr(user, 'id', None))
|
||||
if not task.dify_agent_id:
|
||||
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
|
||||
if cfg_model and cfg_model.dify_system_prompt:
|
||||
cfg_model.dify_system_prompt = None
|
||||
db.session.commit()
|
||||
return jsonify(serialize_task(task))
|
||||
|
||||
@schedule_admin_bp.route('/schedules/<int:task_id>', methods=['DELETE'])
|
||||
@require_admin
|
||||
def delete_schedule(task_id: int):
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
from app.services.schedule.scheduler_service import request_cancel_run
|
||||
running_runs = db.session.query(ScheduleRun).filter(ScheduleRun.schedule_task_id == task_id, ScheduleRun.status == 'running').all()
|
||||
for rr in running_runs:
|
||||
request_cancel_run(rr.id)
|
||||
rr.status = 'failed'
|
||||
rr.error_message = '排程已被删除,执行中断'
|
||||
rr.finished_at = datetime.utcnow()
|
||||
if running_runs:
|
||||
db.session.commit()
|
||||
db.session.query(ScheduleRun).filter(ScheduleRun.schedule_task_id == task_id).delete(synchronize_session=False)
|
||||
db.session.delete(task)
|
||||
db.session.commit()
|
||||
return jsonify({'ok': True})
|
||||
|
||||
@schedule_admin_bp.route('/schedules/<int:task_id>/enable', methods=['POST'])
|
||||
@require_admin
|
||||
def enable_schedule(task_id: int):
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
from app.services.schedule.cron_util import normalize_cron_expr
|
||||
from app.services.schedule.query_service import serialize_task
|
||||
from app.services.schedule.timezone_util import compute_next_run_at
|
||||
|
||||
from app.services.schedule.timezone_util import normalize_schedule_timezone
|
||||
|
||||
task.enabled = True
|
||||
if task.cron_expr:
|
||||
task.cron_expr = normalize_cron_expr(task.cron_expr)
|
||||
task.schedule_timezone = normalize_schedule_timezone(getattr(task, 'schedule_timezone', None))
|
||||
task.next_run_at = compute_next_run_at(task.cron_expr, timezone_name=task.schedule_timezone)
|
||||
db.session.commit()
|
||||
return jsonify(serialize_task(task))
|
||||
|
||||
@schedule_admin_bp.route('/schedules/<int:task_id>/disable', methods=['POST'])
|
||||
@require_admin
|
||||
def disable_schedule(task_id: int):
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
task.enabled = False
|
||||
task.next_run_at = None
|
||||
db.session.commit()
|
||||
return jsonify({'ok': True})
|
||||
|
||||
@schedule_admin_bp.route('/schedules/<int:task_id>/run', methods=['POST'])
|
||||
@require_admin
|
||||
def run_schedule(task_id: int):
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
user = get_current_user()
|
||||
existing = db.session.query(ScheduleRun).filter(ScheduleRun.schedule_task_id == task.id, ScheduleRun.status == 'running').first()
|
||||
if existing:
|
||||
raise ConflictError('该排程正在执行中,请等待完成后再试', details={'run_id': existing.id})
|
||||
run = ScheduleRun(run_no=_generate_run_no(), schedule_task_id=task.id, trigger_type='manual', triggered_by_user_id=getattr(user, 'id', None), started_at=datetime.utcnow(), status='running')
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
app = current_app._get_current_object()
|
||||
run_id = run.id
|
||||
|
||||
def _background():
|
||||
with app.app_context():
|
||||
t = db.session.get(ScheduleTask, task_id)
|
||||
r = db.session.get(ScheduleRun, run_id)
|
||||
if not t or not r:
|
||||
return
|
||||
try:
|
||||
run_task_now(t, trigger_type='manual', triggered_by_user_id=r.triggered_by_user_id, run=r)
|
||||
except Exception as exc:
|
||||
try:
|
||||
r = db.session.get(ScheduleRun, run_id)
|
||||
if r and r.status == 'running':
|
||||
r.status = 'failed'
|
||||
r.error_message = str(exc)
|
||||
r.finished_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
except Exception:
|
||||
db.session.rollback()
|
||||
current_app.logger.error('[schedule-run] run_id=%s failed: %s', run_id, exc, exc_info=True)
|
||||
t = threading.Thread(target=_background, daemon=True, name=f'schedule-run-{run_id}')
|
||||
t.start()
|
||||
fresh = db.session.get(ScheduleRun, run_id)
|
||||
return jsonify(serialize_run(fresh))
|
||||
|
||||
@schedule_admin_bp.route('/schedules/<int:task_id>/runs', methods=['GET'])
|
||||
@require_admin
|
||||
def get_schedule_runs(task_id: int):
|
||||
status = str(request.args.get('status') or '').strip() or None
|
||||
limit = int(request.args.get('limit') or 100)
|
||||
started_after = None
|
||||
started_before = None
|
||||
sa = request.args.get('started_after')
|
||||
sb = request.args.get('started_before')
|
||||
if sa:
|
||||
try:
|
||||
started_after = datetime.fromisoformat(sa.replace('Z', '+00:00'))
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
if sb:
|
||||
try:
|
||||
started_before = datetime.fromisoformat(sb.replace('Z', '+00:00'))
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
return jsonify(list_runs(task_id=task_id, status=status, started_after=started_after, started_before=started_before, limit=limit))
|
||||
|
||||
@schedule_admin_bp.route('/schedule-runs/<int:run_id>', methods=['GET'])
|
||||
@require_admin
|
||||
def get_schedule_run(run_id: int):
|
||||
run = get_run(run_id)
|
||||
if not run:
|
||||
raise NotFoundError('Not found')
|
||||
return jsonify(serialize_run(run))
|
||||
|
||||
@schedule_admin_bp.route('/schedule-runs/<int:run_id>/excel', methods=['GET'])
|
||||
@require_admin
|
||||
def get_schedule_run_excel(run_id: int):
|
||||
from io import BytesIO
|
||||
run = get_run(run_id)
|
||||
if not run:
|
||||
raise NotFoundError('Not found')
|
||||
if not run.excel_file_data:
|
||||
raise NotFoundError('Excel not found')
|
||||
buf = BytesIO(run.excel_file_data)
|
||||
return send_file(buf, as_attachment=True, download_name=run.excel_file_name or 'result.xlsx', mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
|
||||
@@ -1,513 +1,10 @@
|
||||
from __future__ import annotations
|
||||
import threading
|
||||
from datetime import datetime
|
||||
from flask import Blueprint, current_app, jsonify, request, send_file
|
||||
from flask import Response
|
||||
from io import BytesIO
|
||||
import json
|
||||
from app.decorators import require_admin
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, ScheduleTaskConfig
|
||||
from app.auth_jwt import get_current_user
|
||||
from app.services.schedule.query_service import get_run, list_runs, list_tasks, serialize_run, serialize_task
|
||||
from app.services.schedule.scheduler_service import create_task, run_task_now, update_task, _generate_run_no, _generate_test_run_no, _notify_schedule_run_wecom
|
||||
from app.services.schedule.sql_config import get_schedule_sql_config_by_task_id, upsert_schedule_task_config, _build_fetch_sql
|
||||
from app.services.schedule.srm_service import _fetch_records
|
||||
from app.errors import AppError, ValidationError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, ServiceUnavailableError, raise_for_status
|
||||
schedule_admin_bp = Blueprint('schedule_admin', __name__)
|
||||
"""
|
||||
backend/app/api/schedule_admin.py
|
||||
|
||||
def _serialize_task_for_export(task: ScheduleTask, cfg_model: ScheduleTaskConfig | None) -> dict:
|
||||
payload = serialize_task(task)
|
||||
payload['config'] = _serialize_task_config(cfg_model) if cfg_model else None
|
||||
return payload
|
||||
用途:排程 admin API 兼容 shim(Wave 3 迁包过渡期)。
|
||||
依赖:app.api.schedule._legacy。
|
||||
逻辑:旧 import 路径 `from app.api.schedule_admin import schedule_admin_bp` 仍可用;新代码请用 app.api.schedule。
|
||||
"""
|
||||
from app.api.schedule._legacy import schedule_admin_bp
|
||||
|
||||
def _serialize_task_config(cfg_model: ScheduleTaskConfig) -> dict:
|
||||
return {'row_id_key': cfg_model.row_id_key or 'id', 'log_prefix': cfg_model.log_prefix or '', 'base_fetch_sql': cfg_model.base_fetch_sql or '', 'fetch_where_conditions': cfg_model.fetch_where_conditions or '', 'fetch_order_by': cfg_model.fetch_order_by or '', 'writeback_sql': cfg_model.writeback_sql or '', 'detail_sql': cfg_model.detail_sql or '', 'alias_order': cfg_model.alias_order or [], 'detail_alias_order': cfg_model.detail_alias_order or [], 'header_labels': cfg_model.header_labels or {}, 'data_source': {'db_type': cfg_model.ds_db_type or 'sqlserver', 'host': cfg_model.ds_host or '', 'port': cfg_model.ds_port or '', 'database': cfg_model.ds_database or '', 'username': cfg_model.ds_username or '', 'password': cfg_model.ds_password or '', 'driver': cfg_model.ds_driver or '', 'encrypt': cfg_model.ds_encrypt or '', 'trust_cert': cfg_model.ds_trust_cert or ''}, 'external_api': {'url': cfg_model.api_url or '', 'method': cfg_model.api_method or 'POST', 'headers': cfg_model.api_headers or {}, 'body_template': cfg_model.api_body_template or ''}, 'dify_system_prompt': cfg_model.dify_system_prompt or ''}
|
||||
|
||||
@schedule_admin_bp.route('/schedule-config/<int:task_id>', methods=['GET'])
|
||||
@require_admin
|
||||
def get_schedule_task_config(task_id: int):
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
|
||||
if not cfg_model:
|
||||
return jsonify({'data_source_type': task.data_source_type, 'config': None})
|
||||
return jsonify({'data_source_type': task.data_source_type, 'config': _serialize_task_config(cfg_model)})
|
||||
|
||||
@schedule_admin_bp.route('/schedule-config/<int:task_id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_schedule_task_config(task_id: int):
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
data = request.get_json(silent=True) or {}
|
||||
try:
|
||||
if 'data_source_type' in data:
|
||||
task.data_source_type = str(data['data_source_type'])
|
||||
db.session.commit()
|
||||
config_data = data.get('config', data)
|
||||
cfg = upsert_schedule_task_config(task_id, config_data)
|
||||
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
|
||||
return jsonify({'data_source_type': task.data_source_type, 'config': _serialize_task_config(cfg_model) if cfg_model else None})
|
||||
except Exception as e:
|
||||
db.session.rollback()
|
||||
raise ValidationError(str(e))
|
||||
|
||||
@schedule_admin_bp.route('/schedule-config/<int:task_id>/test-sql', methods=['POST'])
|
||||
@require_admin
|
||||
def test_schedule_sql(task_id: int):
|
||||
cfg = get_schedule_sql_config_by_task_id(task_id)
|
||||
if not cfg:
|
||||
raise NotFoundError(f'Config for task {task_id} not found')
|
||||
data = request.get_json(silent=True) or {}
|
||||
custom_where = str(data.get('fetch_where_conditions') or cfg.fetch_where_conditions).strip()
|
||||
custom_order_by = str(data.get('fetch_order_by') or cfg.fetch_order_by).strip()
|
||||
limit = min(int(data.get('limit') or 10), 100)
|
||||
base = cfg.base_fetch_sql or cfg.fetch_sql
|
||||
if cfg.base_fetch_sql:
|
||||
sql = _build_fetch_sql(base, custom_where, custom_order_by)
|
||||
else:
|
||||
sql = base
|
||||
try:
|
||||
from app.services.schedule import _build_srm_conn_str
|
||||
import decimal, datetime
|
||||
if cfg.data_source and (not cfg.data_source.is_empty()):
|
||||
conn_str = cfg.data_source.build_connection_string()
|
||||
else:
|
||||
conn_str = _build_srm_conn_str()
|
||||
rows = _fetch_records(conn_str, sql)
|
||||
|
||||
def _safe(v):
|
||||
if isinstance(v, decimal.Decimal):
|
||||
return float(v)
|
||||
if isinstance(v, (datetime.date, datetime.datetime)):
|
||||
return v.isoformat()
|
||||
if isinstance(v, datetime.timedelta):
|
||||
return str(v)
|
||||
return v
|
||||
result_rows = [{k: _safe(v) for k, v in r.items()} for r in rows[:limit]]
|
||||
return jsonify({'total': len(rows), 'showing': len(result_rows), 'limit': limit, 'sql': sql, 'columns': list(result_rows[0].keys()) if result_rows else [], 'rows': result_rows})
|
||||
except Exception as e:
|
||||
raise AppError(code='SYSTEM.HTTP_ERROR', message=str(e), http_status=400, details={'sql': sql})
|
||||
|
||||
@schedule_admin_bp.route('/schedule-config/<int:task_id>/test-run', methods=['POST'])
|
||||
@require_admin
|
||||
def test_schedule_run(task_id: int):
|
||||
import time as _time
|
||||
from app.services.schedule.excel_service import export_schedule_result_excel
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
cfg = get_schedule_sql_config_by_task_id(task_id)
|
||||
if not cfg:
|
||||
raise NotFoundError(f'Config for task {task_id} not found')
|
||||
data = request.get_json(silent=True) or {}
|
||||
custom_where = str(data.get('fetch_where_conditions') or cfg.fetch_where_conditions).strip()
|
||||
custom_order_by = str(data.get('fetch_order_by') or cfg.fetch_order_by).strip()
|
||||
limit = min(int(data.get('limit') or 3), 10)
|
||||
raw_kb_sync = data.get('kb_sync_enabled', False)
|
||||
if isinstance(raw_kb_sync, str):
|
||||
test_kb_sync_enabled = raw_kb_sync.strip().lower() in ('1', 'true', 'yes', 'on')
|
||||
else:
|
||||
test_kb_sync_enabled = bool(raw_kb_sync)
|
||||
base = cfg.base_fetch_sql or cfg.fetch_sql
|
||||
if cfg.base_fetch_sql:
|
||||
test_sql = _build_fetch_sql(base, custom_where, custom_order_by)
|
||||
else:
|
||||
test_sql = base
|
||||
from app.services.schedule import _build_srm_conn_str, _resolve_dify_agent, _resolve_schedule_user
|
||||
from app.services.schedule.srm_service import _fetch_records, _run_check_job_loop, _build_record_text, _execute_writeback
|
||||
if cfg.data_source and (not cfg.data_source.is_empty()):
|
||||
conn_str = cfg.data_source.build_connection_string()
|
||||
else:
|
||||
conn_str = _build_srm_conn_str()
|
||||
agent = _resolve_dify_agent(task) if task else None
|
||||
user = _resolve_schedule_user(task) if task else 'test_user'
|
||||
wait_seconds = task.wait_seconds if task else 120
|
||||
dify_agent_id = task.dify_agent_id if task else None
|
||||
run = ScheduleRun(run_no=_generate_test_run_no(), schedule_task_id=task_id, trigger_type='test', triggered_by_user_id=getattr(get_current_user(), 'id', None), started_at=datetime.utcnow(), status='running')
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
from app.services.schedule.dify_snapshot import capture_dify_execution_snapshot
|
||||
capture_dify_execution_snapshot(run, task)
|
||||
db.session.commit()
|
||||
if not cfg.fetch_sql:
|
||||
run.status = 'success'
|
||||
run.finished_at = datetime.utcnow()
|
||||
run.error_message = '无抓取SQL,跳过外部系统数据抓取'
|
||||
try:
|
||||
if task.notify_enabled:
|
||||
_notify_schedule_run_wecom(task, run)
|
||||
except Exception as wecom_exc:
|
||||
current_app.logger.error('[schedule-test-run] wecom notify failed: %s', wecom_exc)
|
||||
db.session.commit()
|
||||
return jsonify({'run_no': run.run_no, 'run_id': run.id, 'sql': '', 'limit': 0, 'total_count': 0, 'success_count': 0, 'failed_count': 0, 'skipped_count': 0, 'details': [], 'errors': [], 'step_logs': [{'step': 'no_fetch_sql', 'status': 'skipped', 'detail': '无抓取SQL,跳过外部系统数据抓取'}], 'dify_agent_id': dify_agent_id})
|
||||
|
||||
def _test_fetch_fn(conn_str_arg):
|
||||
return _fetch_records(conn_str_arg, test_sql)
|
||||
|
||||
def _test_writeback_fn(conn_str_arg, *, row_id, run_no, dify_result, dify_message):
|
||||
_execute_writeback(conn_str_arg, cfg.writeback_sql, (run_no, dify_result, dify_message, str(row_id)))
|
||||
test_pre_dify = None
|
||||
test_build_record = None
|
||||
if cfg.detail_sql:
|
||||
|
||||
def _test_pre_dify(conn_str_arg, item, row_id_value):
|
||||
try:
|
||||
detail_rows = _fetch_records(conn_str_arg, cfg.detail_sql, params=(str(row_id_value),))
|
||||
except Exception as detail_exc:
|
||||
return {'dify_result': '人工判定', 'dify_message': f'查询成分明细失败:{detail_exc}', 'writeback_srm': False, 'writeback_err': str(detail_exc)}
|
||||
detail_lines = []
|
||||
for dr in detail_rows:
|
||||
parts = [f"{cfg.header_labels.get(dk, dk)}: {dr.get(dk, '')}" for dk in cfg.detail_alias_order]
|
||||
detail_lines.append(', '.join(parts))
|
||||
item['detail_text'] = '; '.join(detail_lines) if detail_lines else ''
|
||||
item['_detail_rows'] = detail_rows
|
||||
return None
|
||||
test_pre_dify = _test_pre_dify
|
||||
|
||||
def _test_build_with_detail(conn_str_arg, item, row_id_value):
|
||||
detail_rows = item.get('_detail_rows', [])
|
||||
text = _build_record_text(item, cfg.alias_order, cfg.header_labels, detail_rows, cfg.detail_alias_order)
|
||||
return (text, item.get('attachment'))
|
||||
test_build_record = _test_build_with_detail
|
||||
else:
|
||||
|
||||
def _test_build_simple(conn_str_arg, item, row_id_value):
|
||||
text = _build_record_text(item, cfg.alias_order, cfg.header_labels)
|
||||
return (text, item.get('attachment'))
|
||||
test_build_record = _test_build_simple
|
||||
start_ts = _time.time()
|
||||
try:
|
||||
total_count, success_count, failed_count, skipped_count, details, errors, step_logs = _run_check_job_loop(conn_str=conn_str, run_no=run.run_no, agent=agent, user=user, wait_seconds=wait_seconds, run_id=run.id, fetch_fn=_test_fetch_fn, build_record_fn=test_build_record, writeback_fn=_test_writeback_fn, writeback_sql=cfg.writeback_sql, row_id_key=cfg.row_id_key, log_prefix=cfg.log_prefix, fetch_sql=test_sql, max_rows=limit, pre_dify_fn=test_pre_dify, dify_system_prompt=cfg.dify_system_prompt)
|
||||
duration_ms = int((_time.time() - start_ts) * 1000)
|
||||
if total_count == 0 and (not errors):
|
||||
status = 'success'
|
||||
elif failed_count == 0:
|
||||
status = 'success'
|
||||
elif success_count == 0:
|
||||
status = 'failed'
|
||||
else:
|
||||
status = 'partial_failed'
|
||||
header_order = cfg.alias_order if cfg.alias_order else None
|
||||
header_labels = cfg.header_labels if cfg.header_labels else None
|
||||
detail_alias_order = cfg.detail_alias_order or []
|
||||
try:
|
||||
file_data, file_name, file_size = export_schedule_result_excel(run_no=run.run_no, summary={'status': status, 'total_count': total_count, 'success_count': success_count, 'failed_count': failed_count, 'duration_ms': duration_ms}, details=details, header_order=header_order, header_labels=header_labels, detail_alias_order=detail_alias_order)
|
||||
except Exception as excel_exc:
|
||||
current_app.logger.error('[schedule-test-run] excel export failed: %s', excel_exc, exc_info=True)
|
||||
file_data, file_name, file_size = (None, None, 0)
|
||||
run.finished_at = datetime.utcnow()
|
||||
run.duration_ms = duration_ms
|
||||
run.status = status
|
||||
run.total_count = total_count
|
||||
run.success_count = success_count
|
||||
run.failed_count = failed_count
|
||||
run.skipped_count = skipped_count
|
||||
run.step_logs = step_logs if step_logs else None
|
||||
run.error_message = '; '.join(errors[:3]) if errors else None
|
||||
run.excel_file_data = file_data
|
||||
run.excel_file_name = file_name
|
||||
run.excel_file_size = file_size or 0
|
||||
db.session.commit()
|
||||
if test_kb_sync_enabled:
|
||||
try:
|
||||
from app.services.schedule.kb_sync import sync_schedule_run_excel_to_kb
|
||||
|
||||
db.session.refresh(task)
|
||||
db.session.refresh(run)
|
||||
sync_schedule_run_excel_to_kb(task, run, enabled=True, process_inline=True)
|
||||
db.session.refresh(run)
|
||||
except Exception as kb_exc:
|
||||
db.session.rollback()
|
||||
db.session.refresh(run)
|
||||
current_app.logger.error('[schedule-test-run] kb sync failed: %s', kb_exc, exc_info=True)
|
||||
run.kb_sync_status = 'failed'
|
||||
run.kb_group_id = getattr(task, 'kb_group_id', None)
|
||||
run.kb_sync_error = str(kb_exc)
|
||||
db.session.commit()
|
||||
try:
|
||||
if task.notify_enabled:
|
||||
_notify_schedule_run_wecom(task, run)
|
||||
except Exception as wecom_exc:
|
||||
current_app.logger.error('[schedule-test-run] wecom notify failed: %s', wecom_exc)
|
||||
import decimal, datetime as dt
|
||||
|
||||
def _safe(v):
|
||||
if isinstance(v, decimal.Decimal):
|
||||
return float(v)
|
||||
if isinstance(v, (dt.date, dt.datetime)):
|
||||
return v.isoformat()
|
||||
if isinstance(v, dt.timedelta):
|
||||
return str(v)
|
||||
return v
|
||||
safe_details = []
|
||||
for item in details:
|
||||
safe_item = {k: _safe(v) for k, v in item.items()}
|
||||
safe_details.append(safe_item)
|
||||
return jsonify({'run_no': run.run_no, 'run_id': run.id, 'sql': test_sql, 'limit': limit, 'total_count': total_count, 'success_count': success_count, 'failed_count': failed_count, 'skipped_count': skipped_count, 'details': safe_details, 'errors': errors, 'step_logs': step_logs, 'dify_agent_id': dify_agent_id, 'dify_execution_snapshot': run.dify_execution_snapshot, 'kb_sync_status': run.kb_sync_status, 'kb_sync_error': run.kb_sync_error, 'kb_document_id': run.kb_document_id})
|
||||
except Exception as e:
|
||||
db.session.rollback()
|
||||
run = db.session.get(ScheduleRun, run.id)
|
||||
duration_ms = int((_time.time() - start_ts) * 1000)
|
||||
run.finished_at = datetime.utcnow()
|
||||
run.duration_ms = duration_ms
|
||||
run.status = 'failed'
|
||||
run.error_message = str(e)
|
||||
db.session.commit()
|
||||
import traceback
|
||||
raise AppError(code='SYSTEM.HTTP_ERROR', message=str(e), http_status=400, details={'sql': test_sql, 'traceback': traceback.format_exc()})
|
||||
|
||||
@schedule_admin_bp.route('/schedules', methods=['GET'])
|
||||
@require_admin
|
||||
def get_schedules():
|
||||
return jsonify(list_tasks())
|
||||
|
||||
@schedule_admin_bp.route('/schedules/<int:task_id>/export', methods=['GET'])
|
||||
@require_admin
|
||||
def export_schedule(task_id: int):
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
|
||||
payload = {'schema_version': 1, 'exported_at': datetime.utcnow().isoformat(), 'schedules': [_serialize_task_for_export(task, cfg_model)]}
|
||||
body = json.dumps(payload, ensure_ascii=False, indent=2)
|
||||
filename = f"{task.schedule_no or f'schedule_{task.id}'}_export_{datetime.utcnow().strftime('%Y%m%d_%H%M%S')}.json"
|
||||
return Response(body, mimetype='application/json; charset=utf-8', headers={'Content-Disposition': f'attachment; filename="{filename}"'})
|
||||
|
||||
@schedule_admin_bp.route('/schedules/import', methods=['POST'])
|
||||
@require_admin
|
||||
def import_schedules():
|
||||
data = request.get_json(silent=True) or {}
|
||||
schedules = data.get('schedules')
|
||||
if not isinstance(schedules, list):
|
||||
raise ValidationError('Invalid import file: schedules missing')
|
||||
user = get_current_user()
|
||||
imported = 0
|
||||
skipped = 0
|
||||
errors: list[str] = []
|
||||
for item in schedules:
|
||||
if not isinstance(item, dict):
|
||||
skipped += 1
|
||||
continue
|
||||
try:
|
||||
name = str(item.get('name') or '').strip()
|
||||
cron_expr = str(item.get('cron_expr') or '').strip()
|
||||
owner_user_id = int(item.get('owner_user_id'))
|
||||
if not name or not cron_expr:
|
||||
raise ValueError('name or cron_expr missing')
|
||||
existing = None
|
||||
schedule_no = str(item.get('schedule_no') or '').strip()
|
||||
if schedule_no:
|
||||
existing = db.session.query(ScheduleTask).filter_by(schedule_no=schedule_no).first()
|
||||
task_payload = {'name': name, 'schedule_type': str(item.get('schedule_type') or 'platform_app'), 'owner_user_id': owner_user_id, 'cron_expr': cron_expr, 'schedule_timezone': item.get('schedule_timezone'), 'wait_seconds': int(item.get('wait_seconds') or 0), 'dify_agent_id': item.get('dify_agent_id'), 'platform_api_path': item.get('platform_api_path'), 'notify_user_ids_json': item.get('notify_user_ids_json') if isinstance(item.get('notify_user_ids_json'), list) else [], 'notify_enabled': bool(item.get('notify_enabled', True)), 'enabled': bool(item.get('enabled', True)), 'data_source_type': str(item.get('data_source_type') or 'database'), 'kb_sync_enabled': bool(item.get('kb_sync_enabled', False)), 'kb_group_id': item.get('kb_group_id')}
|
||||
cfg = item.get('config') if isinstance(item.get('config'), dict) else None
|
||||
if existing:
|
||||
update_task(existing, payload=task_payload, actor_id=getattr(user, 'id', None))
|
||||
existing.data_source_type = task_payload['data_source_type']
|
||||
if cfg:
|
||||
upsert_schedule_task_config(existing.id, cfg)
|
||||
else:
|
||||
task = create_task(name=name, schedule_type=task_payload['schedule_type'], owner_user_id=owner_user_id, cron_expr=cron_expr, schedule_timezone=task_payload['schedule_timezone'], wait_seconds=task_payload['wait_seconds'], dify_agent_id=task_payload['dify_agent_id'], platform_api_path=task_payload['platform_api_path'], notify_user_ids_json=task_payload['notify_user_ids_json'], notify_enabled=task_payload['notify_enabled'], enabled=task_payload['enabled'], actor_id=getattr(user, 'id', None))
|
||||
task.data_source_type = task_payload['data_source_type']
|
||||
task.kb_sync_enabled = task_payload['kb_sync_enabled']
|
||||
task.kb_group_id = int(task_payload['kb_group_id']) if task_payload.get('kb_group_id') not in (None, '', 0, '0') else None
|
||||
db.session.commit()
|
||||
if cfg:
|
||||
upsert_schedule_task_config(task.id, cfg)
|
||||
imported += 1
|
||||
except Exception as exc:
|
||||
errors.append(str(exc))
|
||||
skipped += 1
|
||||
db.session.commit()
|
||||
return jsonify({'ok': True, 'imported': imported, 'skipped': skipped, 'errors': errors[:20]})
|
||||
|
||||
@schedule_admin_bp.route('/schedules', methods=['POST'])
|
||||
@require_admin
|
||||
def post_schedule():
|
||||
data = request.get_json(silent=True) or {}
|
||||
user = get_current_user()
|
||||
data_source_type = str(data.get('data_source_type') or 'database')
|
||||
task = create_task(name=str(data.get('name') or '').strip(), schedule_type='platform_app', owner_user_id=int(data.get('owner_user_id')), cron_expr=str(data.get('cron_expr') or '').strip(), schedule_timezone=data.get('schedule_timezone'), wait_seconds=int(data.get('wait_seconds') or 0), dify_agent_id=int(data.get('dify_agent_id')) if data.get('dify_agent_id') is not None else None, platform_api_path=str(data.get('platform_api_path') or '').strip() or None, notify_user_ids_json=data.get('notify_user_ids_json') if isinstance(data.get('notify_user_ids_json'), list) else [], notify_enabled=bool(data.get('notify_enabled', True)), enabled=bool(data.get('enabled', True)), actor_id=getattr(user, 'id', None))
|
||||
task.data_source_type = data_source_type
|
||||
task.kb_sync_enabled = bool(data.get('kb_sync_enabled', False))
|
||||
raw_kb_group_id = data.get('kb_group_id')
|
||||
task.kb_group_id = int(raw_kb_group_id) if raw_kb_group_id not in (None, '', 0, '0') else None
|
||||
if data_source_type == 'faq_hot_aggregate':
|
||||
task.platform_api_path = 'faq-aggregate-hot'
|
||||
else:
|
||||
task.platform_api_path = f'/{task.id}'
|
||||
db.session.commit()
|
||||
db.session.refresh(task)
|
||||
config_data = data.get('config')
|
||||
if config_data and data_source_type != 'faq_hot_aggregate':
|
||||
upsert_schedule_task_config(task.id, config_data)
|
||||
if not task.dify_agent_id:
|
||||
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task.id).first()
|
||||
if cfg_model and cfg_model.dify_system_prompt:
|
||||
cfg_model.dify_system_prompt = None
|
||||
db.session.commit()
|
||||
return (jsonify(serialize_task(task)), 201)
|
||||
|
||||
@schedule_admin_bp.route('/schedules/<int:task_id>', methods=['GET'])
|
||||
@require_admin
|
||||
def get_schedule(task_id: int):
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
return jsonify(serialize_task(task))
|
||||
|
||||
@schedule_admin_bp.route('/schedules/<int:task_id>', methods=['PATCH'])
|
||||
@require_admin
|
||||
def patch_schedule(task_id: int):
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
data = request.get_json(silent=True) or {}
|
||||
user = get_current_user()
|
||||
if 'data_source_type' in data:
|
||||
task.data_source_type = str(data['data_source_type'])
|
||||
db.session.commit()
|
||||
config_data = data.get('config')
|
||||
if config_data:
|
||||
upsert_schedule_task_config(task_id, config_data)
|
||||
task = update_task(task, payload=data, actor_id=getattr(user, 'id', None))
|
||||
if not task.dify_agent_id:
|
||||
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
|
||||
if cfg_model and cfg_model.dify_system_prompt:
|
||||
cfg_model.dify_system_prompt = None
|
||||
db.session.commit()
|
||||
return jsonify(serialize_task(task))
|
||||
|
||||
@schedule_admin_bp.route('/schedules/<int:task_id>', methods=['DELETE'])
|
||||
@require_admin
|
||||
def delete_schedule(task_id: int):
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
from app.services.schedule.scheduler_service import request_cancel_run
|
||||
running_runs = db.session.query(ScheduleRun).filter(ScheduleRun.schedule_task_id == task_id, ScheduleRun.status == 'running').all()
|
||||
for rr in running_runs:
|
||||
request_cancel_run(rr.id)
|
||||
rr.status = 'failed'
|
||||
rr.error_message = '排程已被删除,执行中断'
|
||||
rr.finished_at = datetime.utcnow()
|
||||
if running_runs:
|
||||
db.session.commit()
|
||||
db.session.query(ScheduleRun).filter(ScheduleRun.schedule_task_id == task_id).delete(synchronize_session=False)
|
||||
db.session.delete(task)
|
||||
db.session.commit()
|
||||
return jsonify({'ok': True})
|
||||
|
||||
@schedule_admin_bp.route('/schedules/<int:task_id>/enable', methods=['POST'])
|
||||
@require_admin
|
||||
def enable_schedule(task_id: int):
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
from app.services.schedule.cron_util import normalize_cron_expr
|
||||
from app.services.schedule.query_service import serialize_task
|
||||
from app.services.schedule.timezone_util import compute_next_run_at
|
||||
|
||||
from app.services.schedule.timezone_util import normalize_schedule_timezone
|
||||
|
||||
task.enabled = True
|
||||
if task.cron_expr:
|
||||
task.cron_expr = normalize_cron_expr(task.cron_expr)
|
||||
task.schedule_timezone = normalize_schedule_timezone(getattr(task, 'schedule_timezone', None))
|
||||
task.next_run_at = compute_next_run_at(task.cron_expr, timezone_name=task.schedule_timezone)
|
||||
db.session.commit()
|
||||
return jsonify(serialize_task(task))
|
||||
|
||||
@schedule_admin_bp.route('/schedules/<int:task_id>/disable', methods=['POST'])
|
||||
@require_admin
|
||||
def disable_schedule(task_id: int):
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
task.enabled = False
|
||||
task.next_run_at = None
|
||||
db.session.commit()
|
||||
return jsonify({'ok': True})
|
||||
|
||||
@schedule_admin_bp.route('/schedules/<int:task_id>/run', methods=['POST'])
|
||||
@require_admin
|
||||
def run_schedule(task_id: int):
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
user = get_current_user()
|
||||
existing = db.session.query(ScheduleRun).filter(ScheduleRun.schedule_task_id == task.id, ScheduleRun.status == 'running').first()
|
||||
if existing:
|
||||
raise ConflictError('该排程正在执行中,请等待完成后再试', details={'run_id': existing.id})
|
||||
run = ScheduleRun(run_no=_generate_run_no(), schedule_task_id=task.id, trigger_type='manual', triggered_by_user_id=getattr(user, 'id', None), started_at=datetime.utcnow(), status='running')
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
app = current_app._get_current_object()
|
||||
run_id = run.id
|
||||
|
||||
def _background():
|
||||
with app.app_context():
|
||||
t = db.session.get(ScheduleTask, task_id)
|
||||
r = db.session.get(ScheduleRun, run_id)
|
||||
if not t or not r:
|
||||
return
|
||||
try:
|
||||
run_task_now(t, trigger_type='manual', triggered_by_user_id=r.triggered_by_user_id, run=r)
|
||||
except Exception as exc:
|
||||
try:
|
||||
r = db.session.get(ScheduleRun, run_id)
|
||||
if r and r.status == 'running':
|
||||
r.status = 'failed'
|
||||
r.error_message = str(exc)
|
||||
r.finished_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
except Exception:
|
||||
db.session.rollback()
|
||||
current_app.logger.error('[schedule-run] run_id=%s failed: %s', run_id, exc, exc_info=True)
|
||||
t = threading.Thread(target=_background, daemon=True, name=f'schedule-run-{run_id}')
|
||||
t.start()
|
||||
fresh = db.session.get(ScheduleRun, run_id)
|
||||
return jsonify(serialize_run(fresh))
|
||||
|
||||
@schedule_admin_bp.route('/schedules/<int:task_id>/runs', methods=['GET'])
|
||||
@require_admin
|
||||
def get_schedule_runs(task_id: int):
|
||||
status = str(request.args.get('status') or '').strip() or None
|
||||
limit = int(request.args.get('limit') or 100)
|
||||
started_after = None
|
||||
started_before = None
|
||||
sa = request.args.get('started_after')
|
||||
sb = request.args.get('started_before')
|
||||
if sa:
|
||||
try:
|
||||
started_after = datetime.fromisoformat(sa.replace('Z', '+00:00'))
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
if sb:
|
||||
try:
|
||||
started_before = datetime.fromisoformat(sb.replace('Z', '+00:00'))
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
return jsonify(list_runs(task_id=task_id, status=status, started_after=started_after, started_before=started_before, limit=limit))
|
||||
|
||||
@schedule_admin_bp.route('/schedule-runs/<int:run_id>', methods=['GET'])
|
||||
@require_admin
|
||||
def get_schedule_run(run_id: int):
|
||||
run = get_run(run_id)
|
||||
if not run:
|
||||
raise NotFoundError('Not found')
|
||||
return jsonify(serialize_run(run))
|
||||
|
||||
@schedule_admin_bp.route('/schedule-runs/<int:run_id>/excel', methods=['GET'])
|
||||
@require_admin
|
||||
def get_schedule_run_excel(run_id: int):
|
||||
from io import BytesIO
|
||||
run = get_run(run_id)
|
||||
if not run:
|
||||
raise NotFoundError('Not found')
|
||||
if not run.excel_file_data:
|
||||
raise NotFoundError('Excel not found')
|
||||
buf = BytesIO(run.excel_file_data)
|
||||
return send_file(buf, as_attachment=True, download_name=run.excel_file_name or 'result.xlsx', mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
|
||||
__all__ = ['schedule_admin_bp']
|
||||
@@ -2,16 +2,25 @@
|
||||
api/shipping_notice_tools.py
|
||||
|
||||
用途:暴露发货通知 Tool API,供 Dify Chatflow Agent、RPA 回调和导出下载入口调用。
|
||||
依赖:shipping_notice.tools、query_service、openapi_spec、tool_api_url、Flask Blueprint。
|
||||
逻辑:上游由 Dify/OpenAPI 或 RPA 请求进入本文件;本文件做轻量参数编排,再下沉到 services/shipping_notice/* workflow。
|
||||
依赖:app.core.errors、shipping_notice.tools、query_service、openapi_spec、tool_api_url。
|
||||
逻辑:Tool 成功响应仍用 status: ok/failed 业务 envelope;HTTP 级参数/资源错误统一 raise AppError。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
|
||||
from flask import Blueprint, current_app, jsonify, request, send_file
|
||||
|
||||
from app import db
|
||||
from app.errors import AppError, ServiceUnavailableError, UnauthorizedError
|
||||
from app.core.errors import (
|
||||
AppError,
|
||||
NotFoundError,
|
||||
ServiceUnavailableError,
|
||||
UnauthorizedError,
|
||||
ValidationError,
|
||||
)
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
from app.services.shipping_notice.openapi_spec import build_dify_openapi_spec
|
||||
from app.services.shipping_notice.query_service import (
|
||||
EXPORT_MIME_TYPE,
|
||||
get_batch_by_no,
|
||||
@@ -24,8 +33,6 @@ from app.services.shipping_notice.query_service import (
|
||||
serialize_task_summary,
|
||||
task_export_error_message,
|
||||
)
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
from app.services.shipping_notice.openapi_spec import build_dify_openapi_spec
|
||||
from app.services.shipping_notice.tool_api_url import resolve_tool_api_base_url
|
||||
|
||||
shipping_notice_bp = Blueprint("shipping_notice", __name__)
|
||||
@@ -36,48 +43,44 @@ def _require_tool_auth() -> None:
|
||||
校验货代 Tool API 鉴权 Header。
|
||||
【AI 触发时机】:本函数不是给 Agent 直接调用的 Tool;当 Dify、RPA 或外部系统请求本蓝图时由 before_request 自动触发。
|
||||
|
||||
核心逻辑:对齐文件检核 Tool,只接受 `Authorization: Bearer <token>` 或
|
||||
`X-Integration-Key`,并统一使用 `INTEGRATION_API_KEY` 作为服务端校验值;
|
||||
未配置时报服务不可用,缺失或错误时报未授权。
|
||||
核心逻辑:只接受 `Authorization: Bearer <token>` 或 `X-Integration-Key`。
|
||||
货代专用 `SHIPPING_NOTICE_TOOL_API_KEY` 优先,未配置时回退 `INTEGRATION_API_KEY`;
|
||||
未配置任何可用 key 时报服务不可用,缺失或错误时报未授权。
|
||||
"""
|
||||
configured = str(current_app.config.get("INTEGRATION_API_KEY") or "").strip()
|
||||
configured = str(
|
||||
current_app.config.get('SHIPPING_NOTICE_TOOL_API_KEY')
|
||||
or current_app.config.get('INTEGRATION_API_KEY')
|
||||
or ''
|
||||
).strip()
|
||||
if not configured:
|
||||
raise ServiceUnavailableError(
|
||||
"INTEGRATION_API_KEY is not configured",
|
||||
code="missing_auth",
|
||||
'SHIPPING_NOTICE_TOOL_API_KEY or INTEGRATION_API_KEY is not configured',
|
||||
code='missing_auth',
|
||||
)
|
||||
|
||||
bearer = str(request.headers.get("Authorization") or "").strip()
|
||||
token = bearer[7:].strip() if bearer.lower().startswith("bearer ") else ""
|
||||
integration_key = str(request.headers.get("X-Integration-Key") or "").strip()
|
||||
bearer = str(request.headers.get('Authorization') or '').strip()
|
||||
token = bearer[7:].strip() if bearer.lower().startswith('bearer ') else ''
|
||||
integration_key = str(request.headers.get('X-Integration-Key') or '').strip()
|
||||
if configured in {token, integration_key}:
|
||||
return
|
||||
if not token and not integration_key:
|
||||
raise UnauthorizedError("missing_auth")
|
||||
raise UnauthorizedError("invalid_auth")
|
||||
|
||||
if not token and (not integration_key):
|
||||
raise UnauthorizedError('missing_auth')
|
||||
raise UnauthorizedError('invalid_auth')
|
||||
|
||||
def _tool_error_code(exc: AppError) -> str:
|
||||
"""统一归一化 Tool API 的错误码,保持与文件检核 Tool 返回风格一致。"""
|
||||
message = str(exc.message or "").strip()
|
||||
if message in {"missing_auth", "invalid_auth"}:
|
||||
message = str(exc.message or '').strip()
|
||||
if message in {'missing_auth', 'invalid_auth'}:
|
||||
return message
|
||||
if exc.code == "AUTH.UNAUTHORIZED":
|
||||
return "invalid_auth"
|
||||
if exc.code == "SYSTEM.SERVICE_UNAVAILABLE" and "not configured" in message.lower():
|
||||
return "missing_auth"
|
||||
if exc.code == 'AUTH.UNAUTHORIZED':
|
||||
return 'invalid_auth'
|
||||
if exc.code == 'SYSTEM.SERVICE_UNAVAILABLE' and 'not configured' in message.lower():
|
||||
return 'missing_auth'
|
||||
return exc.code
|
||||
|
||||
|
||||
@shipping_notice_bp.errorhandler(AppError)
|
||||
def _handle_tool_app_error(exc: AppError):
|
||||
"""把业务异常统一转成 Tool 侧约定的 JSON 结构。"""
|
||||
return jsonify({
|
||||
"ok": False,
|
||||
"error_code": _tool_error_code(exc),
|
||||
"message": exc.message,
|
||||
}), exc.http_status
|
||||
|
||||
return (jsonify({'ok': False, 'error_code': _tool_error_code(exc), 'message': exc.message}), exc.http_status)
|
||||
|
||||
@shipping_notice_bp.before_request
|
||||
def _verify_tool_access():
|
||||
@@ -85,97 +88,70 @@ def _verify_tool_access():
|
||||
对货代 Tool / RPA / 导出接口做统一 Header 鉴权。
|
||||
核心逻辑:仅放行 OpenAPI 导入文档,其他请求都必须携带有效 Tool Key。
|
||||
"""
|
||||
if request.path.endswith("/openapi.json") or request.path.endswith("/openapi.dify.yaml"):
|
||||
if request.path.endswith('/openapi.json') or request.path.endswith('/openapi.dify.yaml'):
|
||||
return None
|
||||
_require_tool_auth()
|
||||
return None
|
||||
|
||||
|
||||
def _tool_api_base_url() -> str:
|
||||
"""Base URL for OpenAPI servers — hxops backend, NOT Dify (8882)."""
|
||||
return resolve_tool_api_base_url()
|
||||
|
||||
|
||||
def _dify_openapi_spec() -> dict:
|
||||
return build_dify_openapi_spec(_tool_api_base_url())
|
||||
|
||||
|
||||
def _payload() -> dict:
|
||||
return request.get_json(silent=True) or {}
|
||||
|
||||
|
||||
def _generate_batch_no() -> str:
|
||||
from datetime import datetime
|
||||
|
||||
return f"SB-{datetime.utcnow().strftime('%Y%m%d')}-{uuid.uuid4().hex[:8].upper()}"
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/openapi.json", methods=["GET"])
|
||||
@shipping_notice_bp.route('/tools/openapi.json', methods=['GET'])
|
||||
def openapi_spec():
|
||||
"""返回 Dify 导入用的 OpenAPI JSON 文档。"""
|
||||
return jsonify(_dify_openapi_spec())
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/checkpoint-catalog", methods=["GET"])
|
||||
@shipping_notice_bp.route('/tools/checkpoint-catalog', methods=['GET'])
|
||||
def checkpoint_catalog():
|
||||
"""返回检查点目录,供开发联调和文档核对 human_options/action_buttons。"""
|
||||
from app.services.shipping_notice.state_machine import build_checkpoint_catalog
|
||||
|
||||
return jsonify(build_checkpoint_catalog())
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/openapi.dify.yaml", methods=["GET"])
|
||||
@shipping_notice_bp.route('/tools/openapi.dify.yaml', methods=['GET'])
|
||||
def openapi_dify_yaml():
|
||||
"""返回 Dify 导入用的 OpenAPI YAML 文档。"""
|
||||
import yaml
|
||||
|
||||
body = yaml.safe_dump(_dify_openapi_spec(), allow_unicode=True, sort_keys=False)
|
||||
return current_app.response_class(body, mimetype="text/yaml; charset=utf-8")
|
||||
return current_app.response_class(body, mimetype='text/yaml; charset=utf-8')
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/create_task", methods=["POST"])
|
||||
@shipping_notice_bp.route('/tools/create_task', methods=['POST'])
|
||||
def tool_create_task():
|
||||
"""
|
||||
创建单个发货任务。
|
||||
【AI 触发时机】:当用户首次提交一张新的发货通知、当前会话里还没有对应任务时调用。
|
||||
【AI 触发时机】:仅供 Hxops 内部建单链路调用;不是 Dify 画布正式入口。
|
||||
"""
|
||||
return jsonify(shipping_tools.create_task(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/create_batch", methods=["POST"])
|
||||
@shipping_notice_bp.route('/tools/create_batch', methods=['POST'])
|
||||
def tool_create_batch():
|
||||
"""
|
||||
创建或复用发货批次。
|
||||
【AI 触发时机】:当用户一次处理多份发货通知,需要把多任务挂到同一批次时调用。
|
||||
【AI 触发时机】:仅供 Hxops 内部建批链路调用;不是 Dify 画布正式入口。
|
||||
"""
|
||||
payload = _payload()
|
||||
if isinstance(payload.get("notice_items"), list) and payload.get("notice_items"):
|
||||
if isinstance(payload.get('notice_items'), list) and payload.get('notice_items'):
|
||||
return jsonify(shipping_tools.create_batch_tasks(payload))
|
||||
batch_no = str(payload.get("batch_no") or "").strip()
|
||||
batch_no = str(payload.get('batch_no') or '').strip()
|
||||
if batch_no:
|
||||
batch = get_batch_by_no(batch_no)
|
||||
if batch:
|
||||
return jsonify(
|
||||
{
|
||||
"status": "ok",
|
||||
"batch_no": batch.batch_no,
|
||||
"message": f"已复用批次 {batch.batch_no}",
|
||||
"data": serialize_batch_summary(batch),
|
||||
}
|
||||
)
|
||||
return jsonify({'status': 'ok', 'batch_no': batch.batch_no, 'message': f'已复用批次 {batch.batch_no}', 'data': serialize_batch_summary(batch)})
|
||||
batch = shipping_tools.create_batch(payload)
|
||||
db.session.commit()
|
||||
return jsonify(
|
||||
{
|
||||
"status": "ok",
|
||||
"batch_no": batch.batch_no,
|
||||
"message": f"已创建批次 {batch.batch_no}",
|
||||
"data": serialize_batch_summary(batch),
|
||||
}
|
||||
)
|
||||
return jsonify({'status': 'ok', 'batch_no': batch.batch_no, 'message': f'已创建批次 {batch.batch_no}', 'data': serialize_batch_summary(batch)})
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/parse_notice", methods=["POST"])
|
||||
@shipping_notice_bp.route('/tools/parse_notice', methods=['POST'])
|
||||
def tool_parse_notice():
|
||||
"""
|
||||
解析发货通知正文。
|
||||
@@ -183,8 +159,7 @@ def tool_parse_notice():
|
||||
"""
|
||||
return jsonify(shipping_tools.parse_notice(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/update_notice_fields", methods=["POST"])
|
||||
@shipping_notice_bp.route('/tools/update_notice_fields', methods=['POST'])
|
||||
def tool_update_notice_fields():
|
||||
"""
|
||||
修改发货通知单头字段。
|
||||
@@ -192,8 +167,7 @@ def tool_update_notice_fields():
|
||||
"""
|
||||
return jsonify(shipping_tools.update_notice_fields(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/update_notice_line", methods=["POST"])
|
||||
@shipping_notice_bp.route('/tools/update_notice_line', methods=['POST'])
|
||||
def tool_update_notice_line():
|
||||
"""
|
||||
修改指定订单行。
|
||||
@@ -201,8 +175,7 @@ def tool_update_notice_line():
|
||||
"""
|
||||
return jsonify(shipping_tools.update_notice_line(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/add_notice_line", methods=["POST"])
|
||||
@shipping_notice_bp.route('/tools/add_notice_line', methods=['POST'])
|
||||
def tool_add_notice_line():
|
||||
"""
|
||||
新增订单行。
|
||||
@@ -210,8 +183,7 @@ def tool_add_notice_line():
|
||||
"""
|
||||
return jsonify(shipping_tools.add_notice_line(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/remove_notice_line", methods=["POST"])
|
||||
@shipping_notice_bp.route('/tools/remove_notice_line', methods=['POST'])
|
||||
def tool_remove_notice_line():
|
||||
"""
|
||||
删除订单行。
|
||||
@@ -219,8 +191,7 @@ def tool_remove_notice_line():
|
||||
"""
|
||||
return jsonify(shipping_tools.remove_notice_line(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/parse_inventory", methods=["POST"])
|
||||
@shipping_notice_bp.route('/tools/parse_inventory', methods=['POST'])
|
||||
def tool_parse_inventory():
|
||||
"""
|
||||
解析库存内容。
|
||||
@@ -228,19 +199,17 @@ def tool_parse_inventory():
|
||||
"""
|
||||
return jsonify(shipping_tools.parse_inventory(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/upload_inventory_file", methods=["POST"])
|
||||
@shipping_notice_bp.route('/tools/upload_inventory_file', methods=['POST'])
|
||||
def tool_upload_inventory_file():
|
||||
"""
|
||||
服务器侧接收库存 Excel 并解析。
|
||||
【AI 触发时机】:当用户上传库存 Excel,且不希望把二进制文件内容经由 LLM 传输时调用。
|
||||
"""
|
||||
task_id = str(request.form.get("task_id") or request.args.get("task_id") or "").strip()
|
||||
upload = request.files.get("file")
|
||||
task_id = str(request.form.get('task_id') or request.args.get('task_id') or '').strip()
|
||||
upload = request.files.get('file')
|
||||
return jsonify(shipping_tools.upload_inventory_file(task_id, upload))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/get_inventory_schema_preview", methods=["POST"])
|
||||
@shipping_notice_bp.route('/tools/get_inventory_schema_preview', methods=['POST'])
|
||||
def tool_get_inventory_schema_preview():
|
||||
"""
|
||||
获取库存表头预览。
|
||||
@@ -248,8 +217,7 @@ def tool_get_inventory_schema_preview():
|
||||
"""
|
||||
return jsonify(shipping_tools.get_inventory_schema_preview(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/apply_inventory_mapping", methods=["POST"])
|
||||
@shipping_notice_bp.route('/tools/apply_inventory_mapping', methods=['POST'])
|
||||
def tool_apply_inventory_mapping():
|
||||
"""
|
||||
应用库存字段映射。
|
||||
@@ -257,35 +225,31 @@ def tool_apply_inventory_mapping():
|
||||
"""
|
||||
return jsonify(shipping_tools.apply_inventory_mapping(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/ensure_inventory", methods=["POST"])
|
||||
@shipping_notice_bp.route('/tools/ensure_inventory', methods=['POST'])
|
||||
def tool_ensure_inventory():
|
||||
"""
|
||||
保证任务已取得库存数据。
|
||||
【AI 触发时机】:当发货通知已确认,下一步需要让系统拿到库存快照时调用。
|
||||
【AI 触发时机】:仅供后端主调度或内部恢复链路调用;不是 Dify 画布正式入口。
|
||||
"""
|
||||
return jsonify(shipping_tools.ensure_inventory(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/auto_progress", methods=["POST"])
|
||||
@shipping_notice_bp.route('/tools/auto_progress', methods=['POST'])
|
||||
def tool_auto_progress():
|
||||
"""
|
||||
自动推进任务。
|
||||
【AI 触发时机】:当用户说“继续处理”“自动推进”“跑到下一步”时调用。
|
||||
【AI 触发时机】:仅供后端 orchestrator / worker 调用;不是 Dify 画布正式入口。
|
||||
"""
|
||||
return jsonify(shipping_tools.auto_progress(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/match_inventory", methods=["POST"])
|
||||
@shipping_notice_bp.route('/tools/match_inventory', methods=['POST'])
|
||||
def tool_match_inventory():
|
||||
"""
|
||||
执行库存匹配。
|
||||
【AI 触发时机】:当发货通知与库存都已准备好,需要判断是否缺货并生成匹配结果时调用。
|
||||
【AI 触发时机】:仅供后端主调度或内部恢复链路调用;不是 Dify 画布正式入口。
|
||||
"""
|
||||
return jsonify(shipping_tools.match_inventory(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/submit_decision", methods=["POST"])
|
||||
@shipping_notice_bp.route('/tools/submit_decision', methods=['POST'])
|
||||
def tool_submit_decision():
|
||||
"""
|
||||
提交人工决策。
|
||||
@@ -293,26 +257,23 @@ def tool_submit_decision():
|
||||
"""
|
||||
return jsonify(shipping_tools.submit_decision(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/generate_shipment_excel", methods=["POST"])
|
||||
@shipping_notice_bp.route('/tools/generate_shipment_excel', methods=['POST'])
|
||||
def tool_generate_shipment_excel():
|
||||
"""
|
||||
生成出货 Excel。
|
||||
【AI 触发时机】:当库存匹配已通过,用户要求导出货代上传模板时调用。
|
||||
【AI 触发时机】:仅供后端主调度或内部恢复链路调用;不是 Dify 画布正式入口。
|
||||
"""
|
||||
return jsonify(shipping_tools.generate_excel(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/upload_to_freight", methods=["POST"])
|
||||
@shipping_notice_bp.route('/tools/upload_to_freight', methods=['POST'])
|
||||
def tool_upload_to_freight():
|
||||
"""
|
||||
上传到货代系统或确认人工上传完成。
|
||||
【AI 触发时机】:当用户要求推送到货代系统,或确认已手工完成上传时调用。
|
||||
【AI 触发时机】:仅供后端主调度、内部恢复链路或人工上传收口调用;不是 Dify 画布正式入口。
|
||||
"""
|
||||
return jsonify(shipping_tools.upload_to_freight(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/get_task_status", methods=["POST"])
|
||||
@shipping_notice_bp.route('/tools/get_task_status', methods=['POST'])
|
||||
def tool_get_task_status():
|
||||
"""
|
||||
查询任务状态。
|
||||
@@ -320,93 +281,61 @@ def tool_get_task_status():
|
||||
"""
|
||||
return jsonify(shipping_tools.get_task_status(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/get_batch_status", methods=["POST"])
|
||||
@shipping_notice_bp.route('/tools/get_batch_status', methods=['POST'])
|
||||
def tool_get_batch_status():
|
||||
"""
|
||||
查询批次状态。
|
||||
【AI 触发时机】:当用户关注整批任务处理进度,或 Agent 需要查看当前 focus task 与批次摘要时调用。
|
||||
"""
|
||||
payload = _payload()
|
||||
batch_no = str(payload.get("batch_no") or "").strip()
|
||||
batch_no = str(payload.get('batch_no') or '').strip()
|
||||
if not batch_no:
|
||||
return jsonify({"status": "failed", "message": "batch_no is required"}), 400
|
||||
raise ValidationError("batch_no is required")
|
||||
batch = get_batch_by_no(batch_no)
|
||||
if not batch:
|
||||
return jsonify({"status": "failed", "message": "batch not found"}), 404
|
||||
raise NotFoundError("batch not found")
|
||||
focus_task = get_focus_task_for_batch(batch_no, batch.user_id or 0) if batch.user_id is not None else None
|
||||
return jsonify(
|
||||
{
|
||||
"status": "ok",
|
||||
"batch_no": batch.batch_no,
|
||||
"message": f"已获取批次 {batch.batch_no} 状态",
|
||||
"data": {
|
||||
**serialize_batch_summary(batch),
|
||||
"focus_task": serialize_task_summary(focus_task) if focus_task else None,
|
||||
"tasks": list_batch_task_summaries(batch),
|
||||
},
|
||||
}
|
||||
)
|
||||
return jsonify({'status': 'ok', 'batch_no': batch.batch_no, 'message': f'已获取批次 {batch.batch_no} 状态', 'data': {**serialize_batch_summary(batch), 'focus_task': serialize_task_summary(focus_task) if focus_task else None, 'tasks': list_batch_task_summaries(batch)}})
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/switch_focus_task", methods=["POST"])
|
||||
@shipping_notice_bp.route('/tools/switch_focus_task', methods=['POST'])
|
||||
def tool_switch_focus_task():
|
||||
"""
|
||||
切换批次当前焦点任务。
|
||||
【AI 触发时机】:当用户在同一批次里要求“看第 N 个任务”或切换当前处理对象时调用。
|
||||
【AI 触发时机】:当前仅保留给 Hxops 内部切票能力;不属于 Dify 正式导出 Tool。
|
||||
"""
|
||||
payload = _payload()
|
||||
batch_no = str(payload.get("batch_no") or "").strip()
|
||||
task_no = str(payload.get("task_no") or payload.get("target_task_no") or "").strip()
|
||||
batch_no = str(payload.get('batch_no') or '').strip()
|
||||
task_no = str(payload.get('task_no') or payload.get('target_task_no') or '').strip()
|
||||
if not batch_no or not task_no:
|
||||
return jsonify({"status": "failed", "message": "batch_no and task_no are required"}), 400
|
||||
raise ValidationError("batch_no and task_no are required")
|
||||
batch = get_batch_by_no(batch_no)
|
||||
if not batch:
|
||||
return jsonify({"status": "failed", "message": "batch not found"}), 404
|
||||
raise NotFoundError("batch not found")
|
||||
task = get_task_in_batch(batch_no, task_no)
|
||||
if not task:
|
||||
return jsonify({"status": "failed", "message": "task not found in batch"}), 404
|
||||
raise NotFoundError("task not found in batch")
|
||||
batch.current_focus_task_no = task.task_no
|
||||
db.session.commit()
|
||||
return jsonify(
|
||||
{
|
||||
"status": "ok",
|
||||
"batch_no": batch.batch_no,
|
||||
"task_no": task.task_no,
|
||||
"message": f"已切换当前任务到 {task.task_no}",
|
||||
"data": {
|
||||
"batch": serialize_batch_summary(batch),
|
||||
"focus_task": serialize_task_summary(task),
|
||||
},
|
||||
}
|
||||
)
|
||||
return jsonify({'status': 'ok', 'batch_no': batch.batch_no, 'task_no': task.task_no, 'message': f'已切换当前任务到 {task.task_no}', 'data': {'batch': serialize_batch_summary(batch), 'focus_task': serialize_task_summary(task)}})
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/rpa/inventory-ready", methods=["POST"])
|
||||
@shipping_notice_bp.route('/rpa/inventory-ready', methods=['POST'])
|
||||
def rpa_inventory_ready():
|
||||
"""RPA 回调入口:上报库存导出结果并回写任务状态。"""
|
||||
return jsonify(shipping_tools.rpa_report_inventory(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/rpa/upload-complete", methods=["POST"])
|
||||
@shipping_notice_bp.route('/rpa/upload-complete', methods=['POST'])
|
||||
def rpa_upload_complete():
|
||||
"""RPA 回调入口:上报货代上传结果并回写任务状态。"""
|
||||
return jsonify(shipping_tools.rpa_report_upload(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tasks/<task_no>/export", methods=["GET"])
|
||||
@shipping_notice_bp.route('/tasks/<task_no>/export', methods=['GET'])
|
||||
def download_task_export(task_no: str):
|
||||
"""下载任务已生成的出货 Excel。"""
|
||||
task = get_task_by_ref(task_no)
|
||||
err_msg = task_export_error_message(task)
|
||||
if err_msg:
|
||||
return jsonify({"error": err_msg}), 404
|
||||
raise NotFoundError(err_msg)
|
||||
resolved = resolve_task_export_download(task)
|
||||
assert resolved is not None
|
||||
path, download_name = resolved
|
||||
return send_file(
|
||||
path,
|
||||
as_attachment=True,
|
||||
download_name=download_name,
|
||||
mimetype=EXPORT_MIME_TYPE,
|
||||
)
|
||||
return send_file(path, as_attachment=True, download_name=download_name, mimetype=EXPORT_MIME_TYPE)
|
||||
@@ -3,8 +3,8 @@ Speech transcription API — forwards audio to SiliconFlow ASR.
|
||||
"""
|
||||
from flask import Blueprint, jsonify, request
|
||||
|
||||
from app.auth_jwt import get_current_user
|
||||
from app.errors import UnauthorizedError, ValidationError, ServiceUnavailableError
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.errors import UnauthorizedError, ValidationError, ServiceUnavailableError
|
||||
from app.services.speech_asr import SpeechAsrService
|
||||
|
||||
speech_bp = Blueprint('speech', __name__)
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
"""
|
||||
backend/app/api/training.py
|
||||
|
||||
用途:提供新人培训用户侧进度接口与管理端统计导出接口。
|
||||
依赖:JWT 当前用户解析、training_service、Flask Blueprint/send_file。
|
||||
逻辑:员工端负责读写个人培训进度;管理端负责真实记录查询、统计与 Excel 导出。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from io import BytesIO
|
||||
|
||||
from flask import Blueprint, jsonify, request, send_file
|
||||
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.errors import ForbiddenError, UnauthorizedError
|
||||
from app.services.training_service import (
|
||||
export_training_records_excel,
|
||||
get_user_training_record,
|
||||
list_training_records,
|
||||
serialize_training_record,
|
||||
summarize_training_records,
|
||||
upsert_user_training_record,
|
||||
)
|
||||
|
||||
training_user_bp = Blueprint("training_user", __name__)
|
||||
training_admin_bp = Blueprint("training_admin", __name__)
|
||||
|
||||
|
||||
def _require_user():
|
||||
"""确保当前请求存在登录用户。"""
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError()
|
||||
return user
|
||||
|
||||
|
||||
def _require_training_admin():
|
||||
"""确保当前用户具备培训管理权限。"""
|
||||
user = _require_user()
|
||||
if user.role not in {"admin", "hr"}:
|
||||
raise ForbiddenError("Training admin privilege required")
|
||||
return user
|
||||
|
||||
|
||||
@training_user_bp.route("/training-record", methods=["GET"])
|
||||
def get_my_training_record():
|
||||
"""读取当前用户的培训进度;未创建时返回 null data。"""
|
||||
user = _require_user()
|
||||
record = get_user_training_record(user.id)
|
||||
return jsonify(serialize_training_record(record) if record else None)
|
||||
|
||||
|
||||
@training_user_bp.route("/training-record/progress", methods=["PUT"])
|
||||
def save_my_training_record():
|
||||
"""保存当前用户培训进度,用于视频完成、答题推进与结算归档。"""
|
||||
user = _require_user()
|
||||
payload = request.get_json() or {}
|
||||
record = upsert_user_training_record(user, payload)
|
||||
return jsonify(serialize_training_record(record))
|
||||
|
||||
|
||||
@training_admin_bp.route("/training-records", methods=["GET"])
|
||||
def list_admin_training_records():
|
||||
"""列出培训记录,支持关键字、部门、状态筛选。"""
|
||||
_require_training_admin()
|
||||
keyword = request.args.get("keyword")
|
||||
department = request.args.get("department")
|
||||
status = request.args.get("status")
|
||||
|
||||
result = list_training_records(keyword=keyword, department=department, status=status)
|
||||
all_records = list_training_records()
|
||||
department_options = sorted({str(item.department or "").strip() for item in all_records.records if str(item.department or "").strip()})
|
||||
|
||||
page = max(1, request.args.get("page", type=int) or 1)
|
||||
page_size = max(1, min(200, request.args.get("page_size", type=int) or max(result.total, 1)))
|
||||
start = (page - 1) * page_size
|
||||
end = start + page_size
|
||||
items = result.records[start:end]
|
||||
pages = max(1, (result.total + page_size - 1) // page_size) if result.total else 1
|
||||
|
||||
return jsonify(
|
||||
{
|
||||
"items": [serialize_training_record(item) for item in items],
|
||||
"total": result.total,
|
||||
"page": page,
|
||||
"page_size": page_size,
|
||||
"pages": pages,
|
||||
"department_options": department_options,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@training_admin_bp.route("/training-records/stats", methods=["GET"])
|
||||
def get_admin_training_stats():
|
||||
"""返回培训记录聚合统计,供 HR 面板展示。"""
|
||||
_require_training_admin()
|
||||
result = list_training_records(
|
||||
keyword=request.args.get("keyword"),
|
||||
department=request.args.get("department"),
|
||||
status=request.args.get("status"),
|
||||
)
|
||||
return jsonify(summarize_training_records(result.records))
|
||||
|
||||
|
||||
@training_admin_bp.route("/training-records/export", methods=["GET"])
|
||||
def export_admin_training_records():
|
||||
"""导出培训记录为 Excel。"""
|
||||
_require_training_admin()
|
||||
result = list_training_records(
|
||||
keyword=request.args.get("keyword"),
|
||||
department=request.args.get("department"),
|
||||
status=request.args.get("status"),
|
||||
)
|
||||
file_data, file_name = export_training_records_excel(result.records)
|
||||
return send_file(
|
||||
BytesIO(file_data),
|
||||
as_attachment=True,
|
||||
download_name=file_name,
|
||||
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
)
|
||||
+32
-11
@@ -1,11 +1,19 @@
|
||||
"""
|
||||
backend/app/api/user.py
|
||||
|
||||
用途:当前用户域 API(Casdoor 登录、企微 OAuth、首页、FAQ、反馈等)。
|
||||
依赖:app.core.auth.jwt、app.core.errors、models、wecom/dify 相关 services。
|
||||
逻辑:薄路由层鉴权与参数校验;业务编排仍在本文件(Wave 3 拆至 api/user/* + services/user/*)。
|
||||
"""
|
||||
from flask import Blueprint, request, jsonify, current_app
|
||||
from app import db
|
||||
from app.models import User, Agent, QuickQuestion, UserFavoriteAgent, UserDefaultAgent, UserHomepageConfig, Announcement, LoginAudit, WecomCallbackAudit, GeneralFeedback, ChatLog
|
||||
from app.services.feedback_notify import send_feedback_group_notification
|
||||
from app.services.agent_category import serialize_agent_list_item, sort_agent_rows
|
||||
from app.services.wecom_notify import mark_wecom_message_opened, send_wecom_event_message
|
||||
from app.services.wecom_crypto import sha1_hex, decrypt_wecom_aes, extract_encrypt_field
|
||||
from app.auth_jwt import get_current_user as _auth_current_user
|
||||
from app.auth_jwt import issue_local_access_token
|
||||
from app.core.auth.jwt import get_current_user as _auth_current_user
|
||||
from app.core.auth.jwt import issue_local_access_token
|
||||
from sqlalchemy.exc import DatabaseError, IntegrityError, OperationalError
|
||||
from sqlalchemy import and_, or_, inspect, insert
|
||||
from datetime import datetime, timedelta
|
||||
@@ -18,7 +26,16 @@ import base64
|
||||
import json
|
||||
import re
|
||||
import ast
|
||||
from app.errors import AppError, ValidationError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, ServiceUnavailableError, raise_for_status
|
||||
from app.core.errors import (
|
||||
AppError,
|
||||
ConflictError,
|
||||
ForbiddenError,
|
||||
NotFoundError,
|
||||
ServiceUnavailableError,
|
||||
UnauthorizedError,
|
||||
ValidationError,
|
||||
raise_for_status,
|
||||
)
|
||||
user_bp = Blueprint('user', __name__)
|
||||
_WECOM_ACCESS_TOKEN_CACHE = {'token': None, 'expires_at': None}
|
||||
_WECOM_STATE_CACHE = {}
|
||||
@@ -1633,7 +1650,8 @@ def home():
|
||||
if user.role == 'admin':
|
||||
agent_rows = db.session.query(Agent.id, Agent.name, Agent.description, Agent.icon_url, Agent.extra_config).filter(Agent.is_active.is_(True)).all()
|
||||
else:
|
||||
agent_rows = [{'id': agent.id, 'name': agent.name, 'description': agent.description, 'icon_url': agent.icon_url, 'extra_config': agent.extra_config} for agent in user.agents]
|
||||
agent_rows = [{'id': agent.id, 'name': agent.name, 'description': agent.description, 'icon_url': agent.icon_url, 'extra_config': agent.extra_config} for agent in user.agents if agent.is_active]
|
||||
agent_rows = sort_agent_rows(agent_rows)
|
||||
favorites = db.session.query(UserFavoriteAgent).filter_by(user_id=user.id).all()
|
||||
favorite_ids = [f.agent_id for f in favorites]
|
||||
qqs = db.session.query(QuickQuestion).filter(
|
||||
@@ -1650,7 +1668,7 @@ def home():
|
||||
agent = db.session.get(Agent, rel.agent_id)
|
||||
if agent:
|
||||
embedded_agents.append({'id': agent.id, 'name': agent.name, 'iframe_url': agent.extra_config.get('iframe_url') if agent.extra_config else None})
|
||||
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'}, 'agents': [{'id': a.id if hasattr(a, 'id') else a['id'], 'name': a.name if hasattr(a, 'name') else a['name'], 'description': a.description if hasattr(a, 'description') else a['description'], 'icon_url': a.icon_url if hasattr(a, 'icon_url') else a['icon_url'], 'dify_app_type': ((a.extra_config or {}).get('dify_app_type') if hasattr(a, 'extra_config') else (a.get('extra_config') or {}).get('dify_app_type')) or 'chatflow'} 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'}, '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:
|
||||
@@ -2121,12 +2139,15 @@ def get_agent_details(id):
|
||||
if agent_type == 'api' and getattr(agent, 'dify_api_key', None):
|
||||
from app.services.dify import DifyService
|
||||
|
||||
params = DifyService.get_app_parameters(agent)
|
||||
if isinstance(params, dict):
|
||||
dify_parameters = {
|
||||
'file_upload': params.get('file_upload') if isinstance(params.get('file_upload'), dict) else {},
|
||||
'system_parameters': params.get('system_parameters') if isinstance(params.get('system_parameters'), dict) else {},
|
||||
}
|
||||
try:
|
||||
params = DifyService.get_app_parameters(agent)
|
||||
if isinstance(params, dict):
|
||||
dify_parameters = {
|
||||
'file_upload': params.get('file_upload') if isinstance(params.get('file_upload'), dict) else {},
|
||||
'system_parameters': params.get('system_parameters') if isinstance(params.get('system_parameters'), dict) else {},
|
||||
}
|
||||
except Exception as exc:
|
||||
current_app.logger.warning('[user.agents] dify parameters fetch failed agent_id=%s err=%s', id, exc)
|
||||
|
||||
return jsonify({
|
||||
'id': agent.id,
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
backend/app/api/workspace_file_check.py
|
||||
|
||||
用途:工作台文件检核进度轮询 API(对话页 tool_run_progress)。
|
||||
依赖:file_check_tools.chat_log_run_resolver、schedule.query_service。
|
||||
逻辑:前端按 chat_log_id / run_id 轮询检核批次状态与 Excel 链接。
|
||||
依赖:app.core.auth.jwt、app.core.errors、file_check_tools、schedule.query_service。
|
||||
逻辑:鉴权后查询 ScheduleRun 进度;参数缺失 raise ValidationError,资源缺失 raise NotFoundError。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -11,8 +11,8 @@ from io import BytesIO
|
||||
|
||||
from flask import Blueprint, jsonify, request, send_file
|
||||
|
||||
from app.auth_jwt import get_current_user
|
||||
from app.errors import NotFoundError, UnauthorizedError
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.errors import NotFoundError, UnauthorizedError, ValidationError
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
from app.services.file_check_tools.chat_log_run_resolver import find_run_for_chat_log
|
||||
from app.services.schedule.query_service import get_run, serialize_run
|
||||
@@ -21,159 +21,91 @@ workspace_file_check_bp = Blueprint("workspace_file_check", __name__)
|
||||
|
||||
|
||||
def _require_user():
|
||||
"""
|
||||
校验当前登录用户。
|
||||
Raises:
|
||||
UnauthorizedError: 未认证。
|
||||
"""
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError()
|
||||
return user
|
||||
|
||||
|
||||
def serialize_file_judgement(payload: dict) -> dict:
|
||||
"""序列化检核判定统计(读取 response_summary_json.file_judgement)。"""
|
||||
response_summary = payload.get("response_summary_json") if isinstance(payload.get("response_summary_json"), dict) else {}
|
||||
judgement = response_summary.get("file_judgement")
|
||||
response_summary = payload.get('response_summary_json') if isinstance(payload.get('response_summary_json'), dict) else {}
|
||||
judgement = response_summary.get('file_judgement')
|
||||
if not isinstance(judgement, dict):
|
||||
judgement = {}
|
||||
return {
|
||||
"qualified_count": int(judgement.get("qualified_count") or 0),
|
||||
"unqualified_count": int(judgement.get("unqualified_count") or 0),
|
||||
"manual_count": int(judgement.get("manual_count") or 0),
|
||||
"dify_error_count": int(judgement.get("dify_error_count") or 0),
|
||||
"invalid_result_count": int(judgement.get("invalid_result_count") or 0),
|
||||
}
|
||||
|
||||
return {'qualified_count': int(judgement.get('qualified_count') or 0), 'unqualified_count': int(judgement.get('unqualified_count') or 0), 'manual_count': int(judgement.get('manual_count') or 0), 'dify_error_count': int(judgement.get('dify_error_count') or 0), 'invalid_result_count': int(judgement.get('invalid_result_count') or 0)}
|
||||
|
||||
def serialize_current_step(payload: dict) -> dict | None:
|
||||
response_summary = payload.get("response_summary_json") if isinstance(payload.get("response_summary_json"), dict) else {}
|
||||
current_step = response_summary.get("current_step") if isinstance(response_summary.get("current_step"), dict) else None
|
||||
response_summary = payload.get('response_summary_json') if isinstance(payload.get('response_summary_json'), dict) else {}
|
||||
current_step = response_summary.get('current_step') if isinstance(response_summary.get('current_step'), dict) else None
|
||||
if not current_step:
|
||||
return None
|
||||
return {
|
||||
"step": str(current_step.get("step") or ""),
|
||||
"label": str(current_step.get("label") or current_step.get("step") or ""),
|
||||
"row_id": current_step.get("row_id"),
|
||||
"started_at": current_step.get("started_at"),
|
||||
"processed_count": int(current_step.get("processed_count") or 0),
|
||||
"success_count": int(current_step.get("success_count") or 0),
|
||||
"failed_count": int(current_step.get("failed_count") or 0),
|
||||
"skipped_count": int(current_step.get("skipped_count") or 0),
|
||||
}
|
||||
|
||||
return {'step': str(current_step.get('step') or ''), 'label': str(current_step.get('label') or current_step.get('step') or ''), 'row_id': current_step.get('row_id'), 'started_at': current_step.get('started_at'), 'processed_count': int(current_step.get('processed_count') or 0), 'success_count': int(current_step.get('success_count') or 0), 'failed_count': int(current_step.get('failed_count') or 0), 'skipped_count': int(current_step.get('skipped_count') or 0)}
|
||||
|
||||
def _serialize_progress_run(run: ScheduleRun) -> dict:
|
||||
payload = serialize_run(run)
|
||||
total = int(payload.get("total_count") or 0)
|
||||
success = int(payload.get("success_count") or 0)
|
||||
failed = int(payload.get("failed_count") or 0)
|
||||
skipped = int(payload.get("skipped_count") or 0)
|
||||
total = int(payload.get('total_count') or 0)
|
||||
success = int(payload.get('success_count') or 0)
|
||||
failed = int(payload.get('failed_count') or 0)
|
||||
skipped = int(payload.get('skipped_count') or 0)
|
||||
processed = success + failed + skipped
|
||||
percent = int(round((processed / total) * 100)) if total > 0 else 0
|
||||
percent = int(round(processed / total * 100)) if total > 0 else 0
|
||||
percent = max(0, min(percent, 100))
|
||||
return {
|
||||
"run_id": payload["id"],
|
||||
"run_no": payload["run_no"],
|
||||
"task_id": payload["schedule_task_id"],
|
||||
"title": payload.get("schedule_name") or "",
|
||||
"status": payload["status"],
|
||||
"total_count": total,
|
||||
"processed_count": processed,
|
||||
"success_count": success,
|
||||
"failed_count": failed,
|
||||
"skipped_count": skipped,
|
||||
"judgement": serialize_file_judgement(payload),
|
||||
"current_step": serialize_current_step(payload),
|
||||
"progress_percent": percent,
|
||||
"started_at": payload.get("started_at"),
|
||||
"finished_at": payload.get("finished_at"),
|
||||
"duration_ms": payload.get("duration_ms"),
|
||||
"error_message": payload.get("error_message"),
|
||||
"excel": {
|
||||
"file_name": payload.get("excel_file_name"),
|
||||
"file_size": payload.get("excel_file_size"),
|
||||
"download_url": f"/api/workspace/file-check/runs/{run.id}/excel" if payload.get("excel_file_name") else None,
|
||||
},
|
||||
"knowledge_base": {
|
||||
"sync_status": payload.get("kb_sync_status"),
|
||||
"group_id": payload.get("kb_group_id"),
|
||||
"document_id": payload.get("kb_document_id"),
|
||||
"document_version_id": payload.get("kb_document_version_id"),
|
||||
"sync_job_id": payload.get("kb_sync_job_id"),
|
||||
"error_message": payload.get("kb_sync_error"),
|
||||
},
|
||||
}
|
||||
return {'run_id': payload['id'], 'run_no': payload['run_no'], 'task_id': payload['schedule_task_id'], 'title': payload.get('schedule_name') or '', 'status': payload['status'], 'total_count': total, 'processed_count': processed, 'success_count': success, 'failed_count': failed, 'skipped_count': skipped, 'judgement': serialize_file_judgement(payload), 'current_step': serialize_current_step(payload), 'progress_percent': percent, 'started_at': payload.get('started_at'), 'finished_at': payload.get('finished_at'), 'duration_ms': payload.get('duration_ms'), 'error_message': payload.get('error_message'), 'excel': {'file_name': payload.get('excel_file_name'), 'file_size': payload.get('excel_file_size'), 'download_url': f'/api/workspace/file-check/runs/{run.id}/excel' if payload.get('excel_file_name') else None}, 'knowledge_base': {'sync_status': payload.get('kb_sync_status'), 'group_id': payload.get('kb_group_id'), 'document_id': payload.get('kb_document_id'), 'document_version_id': payload.get('kb_document_version_id'), 'sync_job_id': payload.get('kb_sync_job_id'), 'error_message': payload.get('kb_sync_error')}}
|
||||
|
||||
|
||||
@workspace_file_check_bp.route("/file-check/runs/for-log", methods=["GET"])
|
||||
@workspace_file_check_bp.route('/file-check/runs/for-log', methods=['GET'])
|
||||
def workspace_file_check_run_for_log():
|
||||
"""按 chat_log_id + schedule_task_id 返回该轮问答绑定的检核批次。"""
|
||||
_require_user()
|
||||
task_id = request.args.get("task_id", type=int)
|
||||
chat_log_id = request.args.get("chat_log_id", type=int)
|
||||
task_id = request.args.get('task_id', type=int)
|
||||
chat_log_id = request.args.get('chat_log_id', type=int)
|
||||
if not task_id or task_id <= 0:
|
||||
return jsonify({"ok": False, "error": "task_id_required"}), 400
|
||||
raise ValidationError("task_id_required")
|
||||
if not chat_log_id or chat_log_id <= 0:
|
||||
return jsonify({"ok": False, "error": "chat_log_id_required"}), 400
|
||||
|
||||
raise ValidationError("chat_log_id_required")
|
||||
run = find_run_for_chat_log(task_id=task_id, chat_log_id=chat_log_id)
|
||||
return jsonify({
|
||||
"ok": True,
|
||||
"run": _serialize_progress_run(run) if run else None,
|
||||
"match_source": "chat_log" if run else None,
|
||||
})
|
||||
return jsonify({'ok': True, 'run': _serialize_progress_run(run) if run else None, 'match_source': 'chat_log' if run else None})
|
||||
|
||||
|
||||
@workspace_file_check_bp.route("/file-check/runs/for-session", methods=["GET"])
|
||||
@workspace_file_check_bp.route('/file-check/runs/for-session', methods=['GET'])
|
||||
def workspace_file_check_run_for_session():
|
||||
"""已废弃:请改用 for-log?chat_log_id=。保留接口避免旧客户端 404。"""
|
||||
_require_user()
|
||||
return jsonify({"ok": True, "run": None, "match_source": None, "session_updated_at": None})
|
||||
return jsonify({'ok': True, 'run': None, 'match_source': None, 'session_updated_at': None})
|
||||
|
||||
|
||||
@workspace_file_check_bp.route("/file-check/runs/active", methods=["GET"])
|
||||
@workspace_file_check_bp.route('/file-check/runs/active', methods=['GET'])
|
||||
def workspace_file_check_active_run():
|
||||
"""查询当前进行中的检核批次;优先按 schedule_task_id(query: task_id)过滤。"""
|
||||
_require_user()
|
||||
task_id = request.args.get("task_id", type=int)
|
||||
conversation_id = str(request.args.get("conversation_id") or "").strip()
|
||||
query = (
|
||||
ScheduleRun.query.join(ScheduleTask, ScheduleTask.id == ScheduleRun.schedule_task_id)
|
||||
.filter(ScheduleRun.status == "running")
|
||||
)
|
||||
task_id = request.args.get('task_id', type=int)
|
||||
conversation_id = str(request.args.get('conversation_id') or '').strip()
|
||||
query = ScheduleRun.query.join(ScheduleTask, ScheduleTask.id == ScheduleRun.schedule_task_id).filter(ScheduleRun.status == 'running')
|
||||
if task_id is not None:
|
||||
query = query.filter(ScheduleRun.schedule_task_id == task_id)
|
||||
rows = query.order_by(ScheduleRun.id.desc()).all()
|
||||
if task_id is not None:
|
||||
run = rows[0] if rows else None
|
||||
else:
|
||||
run = next((
|
||||
row for row in rows
|
||||
if (
|
||||
not conversation_id
|
||||
or str((row.api_request_json or {}).get("conversation_id") or "").strip() == conversation_id
|
||||
)
|
||||
), None)
|
||||
return jsonify({"ok": True, "run": _serialize_progress_run(run) if run else None})
|
||||
run = next((row for row in rows if not conversation_id or str((row.api_request_json or {}).get('conversation_id') or '').strip() == conversation_id), None)
|
||||
return jsonify({'ok': True, 'run': _serialize_progress_run(run) if run else None})
|
||||
|
||||
|
||||
@workspace_file_check_bp.route("/file-check/runs/<int:run_id>", methods=["GET"])
|
||||
@workspace_file_check_bp.route('/file-check/runs/<int:run_id>', methods=['GET'])
|
||||
def workspace_file_check_run_detail(run_id: int):
|
||||
_require_user()
|
||||
run = get_run(run_id)
|
||||
if not run:
|
||||
raise NotFoundError("run_not_found")
|
||||
return jsonify({"ok": True, "run": _serialize_progress_run(run)})
|
||||
raise NotFoundError('run_not_found')
|
||||
return jsonify({'ok': True, 'run': _serialize_progress_run(run)})
|
||||
|
||||
|
||||
@workspace_file_check_bp.route("/file-check/runs/<int:run_id>/excel", methods=["GET"])
|
||||
@workspace_file_check_bp.route('/file-check/runs/<int:run_id>/excel', methods=['GET'])
|
||||
def workspace_file_check_run_excel(run_id: int):
|
||||
_require_user()
|
||||
run = get_run(run_id)
|
||||
if not run:
|
||||
raise NotFoundError("run_not_found")
|
||||
raise NotFoundError('run_not_found')
|
||||
if not run.excel_file_data:
|
||||
raise NotFoundError("excel_not_found")
|
||||
return send_file(
|
||||
BytesIO(run.excel_file_data),
|
||||
as_attachment=True,
|
||||
download_name=run.excel_file_name or f"{run.run_no}.xlsx",
|
||||
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
)
|
||||
raise NotFoundError('excel_not_found')
|
||||
return send_file(BytesIO(run.excel_file_data), as_attachment=True, download_name=run.excel_file_name or f'{run.run_no}.xlsx', mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
|
||||
@@ -1,49 +1,80 @@
|
||||
"""
|
||||
backend/app/api/workspace_schedule.py
|
||||
|
||||
用途:工作台排程运行记录查询 API。
|
||||
依赖:app.core.auth.jwt、app.core.errors、schedule.query_service。
|
||||
逻辑:鉴权后只读查询 ScheduleRun;未登录 raise UnauthorizedError。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from flask import Blueprint, jsonify, request, send_file
|
||||
from app.auth_jwt import get_current_user
|
||||
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.errors import ForbiddenError, NotFoundError, UnauthorizedError
|
||||
from app.services.schedule.query_service import can_view_run, get_run, list_runs, serialize_run
|
||||
from app.errors import AppError, ValidationError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, ServiceUnavailableError, raise_for_status
|
||||
workspace_schedule_bp = Blueprint('workspace_schedule', __name__)
|
||||
|
||||
workspace_schedule_bp = Blueprint("workspace_schedule", __name__)
|
||||
|
||||
|
||||
def _require_user():
|
||||
"""校验当前用户;未登录时抛出 UnauthorizedError。"""
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError()
|
||||
return user
|
||||
|
||||
@workspace_schedule_bp.route('/schedule-runs', methods=['GET'])
|
||||
|
||||
@workspace_schedule_bp.route("/schedule-runs", methods=["GET"])
|
||||
def workspace_schedule_runs():
|
||||
user = _require_user()
|
||||
status = str(request.args.get('status') or '').strip() or None
|
||||
schedule_name = str(request.args.get('schedule_name') or '').strip() or None
|
||||
started_after_str = request.args.get('started_after')
|
||||
started_before_str = request.args.get('started_before')
|
||||
started_after = datetime.fromisoformat(started_after_str.replace('Z', '+00:00')) if started_after_str else None
|
||||
started_before = datetime.fromisoformat(started_before_str.replace('Z', '+00:00')) if started_before_str else None
|
||||
limit = int(request.args.get('limit') or 100)
|
||||
return jsonify(list_runs(notify_user_id=user.id, schedule_name=schedule_name, status=status, started_after=started_after, started_before=started_before, limit=limit))
|
||||
status = str(request.args.get("status") or "").strip() or None
|
||||
schedule_name = str(request.args.get("schedule_name") or "").strip() or None
|
||||
started_after_str = request.args.get("started_after")
|
||||
started_before_str = request.args.get("started_before")
|
||||
started_after = datetime.fromisoformat(started_after_str.replace("Z", "+00:00")) if started_after_str else None
|
||||
started_before = datetime.fromisoformat(started_before_str.replace("Z", "+00:00")) if started_before_str else None
|
||||
limit = int(request.args.get("limit") or 100)
|
||||
return jsonify(
|
||||
list_runs(
|
||||
notify_user_id=user.id,
|
||||
schedule_name=schedule_name,
|
||||
status=status,
|
||||
started_after=started_after,
|
||||
started_before=started_before,
|
||||
limit=limit,
|
||||
)
|
||||
)
|
||||
|
||||
@workspace_schedule_bp.route('/schedule-runs/<int:run_id>', methods=['GET'])
|
||||
|
||||
@workspace_schedule_bp.route("/schedule-runs/<int:run_id>", methods=["GET"])
|
||||
def workspace_schedule_run_detail(run_id: int):
|
||||
user = _require_user()
|
||||
run = get_run(run_id)
|
||||
if not run:
|
||||
raise NotFoundError('Not found')
|
||||
raise NotFoundError("Not found")
|
||||
if not can_view_run(run, user.id):
|
||||
raise ForbiddenError('Forbidden')
|
||||
raise ForbiddenError("Forbidden")
|
||||
return jsonify(serialize_run(run))
|
||||
|
||||
@workspace_schedule_bp.route('/schedule-runs/<int:run_id>/excel', methods=['GET'])
|
||||
|
||||
@workspace_schedule_bp.route("/schedule-runs/<int:run_id>/excel", methods=["GET"])
|
||||
def workspace_schedule_run_excel(run_id: int):
|
||||
from io import BytesIO
|
||||
|
||||
user = _require_user()
|
||||
run = get_run(run_id)
|
||||
if not run:
|
||||
raise NotFoundError('Not found')
|
||||
raise NotFoundError("Not found")
|
||||
if not can_view_run(run, user.id):
|
||||
raise ForbiddenError('Forbidden')
|
||||
raise ForbiddenError("Forbidden")
|
||||
if not run.excel_file_data:
|
||||
raise NotFoundError('Excel not found')
|
||||
raise NotFoundError("Excel not found")
|
||||
buf = BytesIO(run.excel_file_data)
|
||||
return send_file(buf, as_attachment=True, download_name=run.excel_file_name or 'result.xlsx', mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
|
||||
return send_file(
|
||||
buf,
|
||||
as_attachment=True,
|
||||
download_name=run.excel_file_name or "result.xlsx",
|
||||
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
)
|
||||
@@ -2,22 +2,28 @@
|
||||
api/workspace_shipping_notice.py
|
||||
|
||||
用途:提供 HXOPS 工作台与聊天前端使用的发货通知用户态 API。
|
||||
依赖:auth_jwt、query_service、shipping_notice.tools、notice_upload、chat_actions。
|
||||
逻辑:前端通过本 Blueprint 访问用户鉴权路由;本文件做权限校验与参数编排,再调用 shipping_notice service/workflow 返回页面所需数据。
|
||||
依赖:app.core.auth.jwt、app.core.errors、shipping_notice.query_service / tools / notice_upload。
|
||||
逻辑:薄路由层做鉴权与参数校验(统一 raise AppError);业务编排下沉 shipping_notice service。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import Blueprint, jsonify, request, send_file
|
||||
|
||||
from app import db
|
||||
from app.auth_jwt import get_current_user
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.errors import AppError, NotFoundError, UnauthorizedError, ValidationError
|
||||
from app.models import ShippingBatch, ShippingTask
|
||||
from app.services.shipping_notice.chat_actions import build_chat_actions_payload
|
||||
from app.services.shipping_notice.constants import CP_EXPORT_GENERATED, CP_NOTICE_TEXT_EXTRACTION_FAILED, AUTO_CHAIN_FALLBACK, MAP_JSON
|
||||
from app.services.shipping_notice.constants import (
|
||||
AUTO_CHAIN_FALLBACK,
|
||||
CP_EXPORT_GENERATED,
|
||||
CP_NOTICE_TEXT_EXTRACTION_FAILED,
|
||||
MAP_JSON,
|
||||
)
|
||||
from app.services.shipping_notice.query_service import (
|
||||
EXPORT_MIME_TYPE,
|
||||
get_batch_for_user,
|
||||
get_conversation_batch_workspace,
|
||||
get_focus_task_for_batch,
|
||||
get_task_for_user,
|
||||
list_batches_for_user,
|
||||
@@ -34,649 +40,520 @@ workspace_shipping_notice_bp = Blueprint("workspace_shipping_notice", __name__)
|
||||
|
||||
|
||||
def _require_user():
|
||||
"""校验当前请求用户,统一返回 `(user, error_response)` 结构。"""
|
||||
"""
|
||||
校验当前登录用户;未认证时抛出 UnauthorizedError,由全局 handler 输出标准错误 JSON。
|
||||
Returns:
|
||||
User 模型实例。
|
||||
Raises:
|
||||
UnauthorizedError: 无有效 JWT 或 legacy header。
|
||||
"""
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
return None, (jsonify({"error": "Unauthorized"}), 401)
|
||||
return user, None
|
||||
raise UnauthorizedError()
|
||||
return user
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks", methods=["GET"])
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks', methods=['GET'])
|
||||
def workspace_shipping_tasks():
|
||||
"""列出当前用户可见的发货任务,可按批次与处理状态过滤。"""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
batch_no = str(request.args.get("batch_no") or "").strip() or None
|
||||
process_status = str(request.args.get("process_status") or "").strip() or None
|
||||
limit = int(request.args.get("limit") or 100)
|
||||
user = _require_user()
|
||||
batch_no = str(request.args.get('batch_no') or '').strip() or None
|
||||
process_status = str(request.args.get('process_status') or '').strip() or None
|
||||
limit = int(request.args.get('limit') or 100)
|
||||
return jsonify(list_tasks_for_user(user.id, batch_no=batch_no, process_status=process_status, limit=limit))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-batches", methods=["GET"])
|
||||
@workspace_shipping_notice_bp.route('/shipping-batches', methods=['GET'])
|
||||
def workspace_shipping_batches():
|
||||
"""列出当前用户的发货批次摘要。"""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
limit = int(request.args.get("limit") or 100)
|
||||
user = _require_user()
|
||||
limit = int(request.args.get('limit') or 100)
|
||||
return jsonify(list_batches_for_user(user.id, limit=limit))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-conversations/<conversation_id>/batch-workspace', methods=['GET'])
|
||||
def workspace_shipping_conversation_batch_workspace(conversation_id: str):
|
||||
"""返回一个 Agent 会话下的多批次执行工作台快照。"""
|
||||
user = _require_user()
|
||||
batches = ShippingBatch.query.filter(ShippingBatch.conversation_id == str(conversation_id or "").strip()).filter(
|
||||
(ShippingBatch.user_id == user.id) | (ShippingBatch.user_id.is_(None))
|
||||
).all()
|
||||
return jsonify(get_conversation_batch_workspace(conversation_id, user.id))
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-batches/create-from-notices", methods=["POST"])
|
||||
@workspace_shipping_notice_bp.route('/shipping-batches/create-from-notices', methods=['POST'])
|
||||
def workspace_create_shipping_batch_from_notices():
|
||||
"""接收多份发货通知附件,创建批次并交给后台编排器逐票推进。"""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
|
||||
uploads = request.files.getlist("files")
|
||||
user = _require_user()
|
||||
uploads = request.files.getlist('files')
|
||||
if not uploads:
|
||||
single = request.files.get("file")
|
||||
single = request.files.get('file')
|
||||
if single:
|
||||
uploads = [single]
|
||||
if not uploads:
|
||||
return jsonify({"error": "files is required"}), 400
|
||||
|
||||
raise ValidationError('files is required')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
from app.services.shipping_notice.notice_upload import (
|
||||
extract_notice_text,
|
||||
guess_source_type,
|
||||
max_notice_chars,
|
||||
save_task_notice_upload,
|
||||
)
|
||||
|
||||
conversation_id = str(request.form.get("conversation_id") or "").strip()
|
||||
from app.services.shipping_notice.notice_upload import extract_notice_text, guess_source_type, max_notice_chars, save_task_notice_upload
|
||||
conversation_id = str(request.form.get('conversation_id') or '').strip()
|
||||
notice_items: list[dict] = []
|
||||
for upload in uploads:
|
||||
raw = upload.read() or b""
|
||||
filename = upload.filename or "notice"
|
||||
raw = upload.read() or b''
|
||||
filename = upload.filename or 'notice'
|
||||
source_type = guess_source_type(filename)
|
||||
text = ""
|
||||
text = ''
|
||||
warnings: list[str] = []
|
||||
try:
|
||||
temp_task_no = f"TMP-{len(notice_items) + 1}"
|
||||
temp_task_no = f'TMP-{len(notice_items) + 1}'
|
||||
saved_path = save_task_notice_upload(temp_task_no, filename, raw)
|
||||
text, meta = extract_notice_text(saved_path)
|
||||
warnings = list(meta.get("warnings") or []) if isinstance(meta, dict) else []
|
||||
warnings = list(meta.get('warnings') or []) if isinstance(meta, dict) else []
|
||||
except Exception as exc:
|
||||
warnings = [f"notice_extract_failed:{exc}"]
|
||||
warnings = [f'notice_extract_failed:{exc}']
|
||||
if text:
|
||||
limit = max_notice_chars()
|
||||
if len(text) > limit:
|
||||
text = text[:limit]
|
||||
warnings.append(f"notice_text_truncated:{limit}")
|
||||
notice_items.append(
|
||||
{
|
||||
"source_type": source_type,
|
||||
"source_file_name": filename,
|
||||
"source_file_type": str(getattr(upload, "mimetype", "") or "").strip() or None,
|
||||
"raw_text": text,
|
||||
"warnings": warnings,
|
||||
}
|
||||
)
|
||||
|
||||
payload = {
|
||||
"user_id": user.id,
|
||||
"conversation_id": conversation_id or None,
|
||||
"file_count": len(notice_items),
|
||||
"notice_items": notice_items,
|
||||
# 上传接口先快速完成建批/建任务与 raw_text 落库,避免请求阻塞;
|
||||
# 后续首轮解析与可自动推进步骤交给后台编排线程逐票执行。
|
||||
"defer_parse": True,
|
||||
}
|
||||
warnings.append(f'notice_text_truncated:{limit}')
|
||||
notice_items.append({'source_type': source_type, 'source_file_name': filename, 'source_file_type': str(getattr(upload, 'mimetype', '') or '').strip() or None, 'raw_text': text, 'warnings': warnings})
|
||||
payload = {'user_id': user.id, 'conversation_id': conversation_id or None, 'file_count': len(notice_items), 'notice_items': notice_items, 'defer_parse': True}
|
||||
created = shipping_tools.create_batch_tasks(payload)
|
||||
data = created.get("data") if isinstance(created, dict) else None
|
||||
batch_data = data.get("batch") if isinstance(data, dict) else None
|
||||
tasks_data = data.get("tasks") if isinstance(data, dict) else None
|
||||
batch_no = str(created.get("batch_no") or (batch_data or {}).get("batch_no") or "").strip()
|
||||
data = created.get('data') if isinstance(created, dict) else None
|
||||
batch_data = data.get('batch') if isinstance(data, dict) else None
|
||||
tasks_data = data.get('tasks') if isinstance(data, dict) else None
|
||||
batch_no = str(created.get('batch_no') or (batch_data or {}).get('batch_no') or '').strip()
|
||||
orchestrator_started = False
|
||||
if batch_no:
|
||||
from app.services.shipping_notice.batch_orchestrator import start_batch_orchestrator
|
||||
|
||||
orchestrator_started = start_batch_orchestrator(batch_no)
|
||||
if isinstance(data, dict) and batch_no:
|
||||
focus_task = get_focus_task_for_batch(batch_no, user.id)
|
||||
if focus_task:
|
||||
data["focus_task"] = serialize_task_summary(focus_task)
|
||||
data['focus_task'] = serialize_task_summary(focus_task)
|
||||
if isinstance(tasks_data, list):
|
||||
data["tasks"] = tasks_data
|
||||
data["orchestrator_started"] = orchestrator_started
|
||||
data['tasks'] = tasks_data
|
||||
data['orchestrator_started'] = orchestrator_started
|
||||
if isinstance(created, dict):
|
||||
base_message = str(created.get("message") or "").strip()
|
||||
base_message = str(created.get('message') or '').strip()
|
||||
if orchestrator_started:
|
||||
created["message"] = (
|
||||
f"{base_message},后台已开始逐票处理。"
|
||||
if base_message
|
||||
else "后台已开始逐票处理。"
|
||||
)
|
||||
created['message'] = f'{base_message},后台已开始逐票处理。' if base_message else '后台已开始逐票处理。'
|
||||
return jsonify(created)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-batches/<batch_no>", methods=["GET"])
|
||||
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>', methods=['GET'])
|
||||
def workspace_shipping_batch_detail(batch_no: str):
|
||||
"""返回批次详情、批次内任务列表和当前焦点任务。"""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
user = _require_user()
|
||||
batch = get_batch_for_user(batch_no, user.id)
|
||||
if not batch:
|
||||
return jsonify({"error": "Not found"}), 404
|
||||
raise NotFoundError('Not found')
|
||||
focus_task = get_focus_task_for_batch(batch_no, user.id)
|
||||
return jsonify(
|
||||
{
|
||||
**serialize_batch_summary(batch),
|
||||
"tasks": list_tasks_for_batch(batch_no, user.id),
|
||||
"focus_task": serialize_task_summary(focus_task) if focus_task else None,
|
||||
}
|
||||
)
|
||||
return jsonify({**serialize_batch_summary(batch), 'tasks': list_tasks_for_batch(batch_no, user.id), 'focus_task': serialize_task_summary(focus_task) if focus_task else None})
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-batches/<batch_no>/tasks", methods=["GET"])
|
||||
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>/tasks', methods=['GET'])
|
||||
def workspace_shipping_batch_tasks(batch_no: str):
|
||||
"""返回指定批次下的任务列表。"""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
user = _require_user()
|
||||
batch = get_batch_for_user(batch_no, user.id)
|
||||
if not batch:
|
||||
return jsonify({"error": "Not found"}), 404
|
||||
raise NotFoundError('Not found')
|
||||
return jsonify(list_tasks_for_batch(batch_no, user.id))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-batches/<batch_no>/focus-task", methods=["GET"])
|
||||
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>/focus-task', methods=['GET'])
|
||||
def workspace_shipping_batch_focus_task(batch_no: str):
|
||||
"""返回指定批次当前焦点任务的摘要。"""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
user = _require_user()
|
||||
batch = get_batch_for_user(batch_no, user.id)
|
||||
if not batch:
|
||||
return jsonify({"error": "Not found"}), 404
|
||||
raise NotFoundError('Not found')
|
||||
focus_task = get_focus_task_for_batch(batch_no, user.id)
|
||||
if not focus_task:
|
||||
return jsonify({"error": "Focus task not found"}), 404
|
||||
raise NotFoundError('Focus task not found')
|
||||
return jsonify(serialize_task_summary(focus_task))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-batches/<batch_no>/focus-task", methods=["POST"])
|
||||
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>/focus-task', methods=['POST'])
|
||||
def workspace_switch_shipping_batch_focus_task(batch_no: str):
|
||||
"""切换批次当前焦点任务,供工作台在同批次任务间跳转。"""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
user = _require_user()
|
||||
batch = get_batch_for_user(batch_no, user.id)
|
||||
if not batch:
|
||||
return jsonify({"error": "Not found"}), 404
|
||||
raise NotFoundError('Not found')
|
||||
data = request.get_json(silent=True) or {}
|
||||
task_no = str(data.get("task_no") or data.get("target_task_no") or "").strip()
|
||||
task_no = str(data.get('task_no') or data.get('target_task_no') or '').strip()
|
||||
if not task_no:
|
||||
return jsonify({"error": "task_no is required"}), 400
|
||||
raise ValidationError('task_no is required')
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task or task.batch_id != batch.id:
|
||||
return jsonify({"error": "Task not found in batch"}), 404
|
||||
raise NotFoundError('Task not found in batch')
|
||||
batch.current_focus_task_no = task.task_no
|
||||
db.session.commit()
|
||||
return jsonify(
|
||||
{
|
||||
"batch": serialize_batch_summary(batch),
|
||||
"focus_task": serialize_task_summary(task),
|
||||
}
|
||||
)
|
||||
return jsonify({'batch': serialize_batch_summary(batch), 'focus_task': serialize_task_summary(task)})
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks", methods=["POST"])
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks', methods=['POST'])
|
||||
def workspace_create_shipping_task():
|
||||
"""创建单个发货任务,适用于手工录入或聊天入口先建单。"""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
user = _require_user()
|
||||
data = request.get_json(silent=True) or {}
|
||||
payload = {"user_id": user.id}
|
||||
source_type = str(data.get("source_type") or "").strip()
|
||||
payload = {'user_id': user.id}
|
||||
source_type = str(data.get('source_type') or '').strip()
|
||||
if source_type:
|
||||
payload["source_type"] = source_type
|
||||
conversation_id = str(data.get("conversation_id") or "").strip()
|
||||
payload['source_type'] = source_type
|
||||
conversation_id = str(data.get('conversation_id') or '').strip()
|
||||
if conversation_id:
|
||||
payload["conversation_id"] = conversation_id
|
||||
raw_content = str(data.get("raw_content") or "").strip()
|
||||
payload['conversation_id'] = conversation_id
|
||||
raw_content = str(data.get('raw_content') or '').strip()
|
||||
if raw_content:
|
||||
payload["raw_content"] = raw_content
|
||||
|
||||
payload['raw_content'] = raw_content
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
|
||||
return jsonify(shipping_tools.create_task(payload))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks/create-from-notice", methods=["POST"])
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/create-from-notice', methods=['POST'])
|
||||
def workspace_create_shipping_task_from_notice():
|
||||
"""接收单个发货通知附件,建单后抽取文本并保存 raw_text,再交给后台编排器。"""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
|
||||
upload = request.files.get("file")
|
||||
user = _require_user()
|
||||
upload = request.files.get('file')
|
||||
if not upload:
|
||||
return jsonify({"error": "file is required"}), 400
|
||||
|
||||
raise ValidationError('file is required')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
from app.services.shipping_notice.notice_upload import (
|
||||
extract_notice_text,
|
||||
guess_source_type,
|
||||
max_notice_chars,
|
||||
save_task_notice_upload,
|
||||
)
|
||||
|
||||
source_type = guess_source_type(upload.filename or "")
|
||||
conversation_id = str(request.form.get("conversation_id") or "").strip()
|
||||
payload = {"user_id": user.id, "source_type": source_type}
|
||||
from app.services.shipping_notice.notice_upload import extract_notice_text, guess_source_type, max_notice_chars, save_task_notice_upload
|
||||
source_type = guess_source_type(upload.filename or '')
|
||||
conversation_id = str(request.form.get('conversation_id') or '').strip()
|
||||
payload = {'user_id': user.id, 'source_type': source_type}
|
||||
if conversation_id:
|
||||
payload["conversation_id"] = conversation_id
|
||||
payload['conversation_id'] = conversation_id
|
||||
created = shipping_tools.create_task(payload)
|
||||
task_id = str(created.get("task_id") or "").strip()
|
||||
task_id = str(created.get('task_id') or '').strip()
|
||||
if not task_id:
|
||||
return jsonify({"error": "failed to create task"}), 500
|
||||
|
||||
raw = upload.read() or b""
|
||||
saved_path = save_task_notice_upload(task_id, upload.filename or "notice", raw)
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='failed to create task', http_status=500)
|
||||
raw = upload.read() or b''
|
||||
saved_path = save_task_notice_upload(task_id, upload.filename or 'notice', raw)
|
||||
text, meta = extract_notice_text(saved_path)
|
||||
if not text:
|
||||
from app.services.shipping_notice.state_machine import action_buttons_for_checkpoint
|
||||
|
||||
return jsonify(
|
||||
{
|
||||
"status": "needs_human",
|
||||
"task_id": task_id,
|
||||
"message": "未能从附件抽取到可解析文本(可能是扫描件/OCR 不可用)。请复制粘贴文本,或更换清晰版文件后重试。",
|
||||
"data": {"notice_upload": {"filename": upload.filename or "", **meta}},
|
||||
"human_options": ["reparse", "reject"],
|
||||
"checkpoint": CP_NOTICE_TEXT_EXTRACTION_FAILED,
|
||||
"action_buttons": action_buttons_for_checkpoint(CP_NOTICE_TEXT_EXTRACTION_FAILED),
|
||||
}
|
||||
)
|
||||
|
||||
return jsonify({'status': 'needs_human', 'task_id': task_id, 'message': '未能从附件抽取到可解析文本(可能是扫描件/OCR 不可用)。请复制粘贴文本,或更换清晰版文件后重试。', 'data': {'notice_upload': {'filename': upload.filename or '', **meta}}, 'human_options': ['reparse', 'reject'], 'checkpoint': CP_NOTICE_TEXT_EXTRACTION_FAILED, 'action_buttons': action_buttons_for_checkpoint(CP_NOTICE_TEXT_EXTRACTION_FAILED)})
|
||||
if text:
|
||||
limit = max_notice_chars()
|
||||
if len(text) > limit:
|
||||
text = text[:limit]
|
||||
meta.setdefault("warnings", []).append(f"notice_text_truncated:{limit}")
|
||||
meta.setdefault('warnings', []).append(f'notice_text_truncated:{limit}')
|
||||
task = ShippingTask.query.filter_by(task_no=task_id).first()
|
||||
if task:
|
||||
task.raw_content = text
|
||||
db.session.commit()
|
||||
|
||||
task = ShippingTask.query.filter_by(task_no=task_id).first()
|
||||
if task:
|
||||
task.source_file_name = str(upload.filename or "").strip() or task.source_file_name
|
||||
task.source_file_type = str(getattr(upload, "mimetype", "") or "").strip() or task.source_file_type
|
||||
task.source_file_name = str(upload.filename or '').strip() or task.source_file_name
|
||||
task.source_file_type = str(getattr(upload, 'mimetype', '') or '').strip() or task.source_file_type
|
||||
db.session.commit()
|
||||
|
||||
from app.services.shipping_notice.batch_orchestrator import start_task_orchestrator
|
||||
|
||||
orchestrator_started = start_task_orchestrator(task_id)
|
||||
return jsonify(
|
||||
{
|
||||
"status": "ok",
|
||||
"task_id": task_id,
|
||||
"message": (
|
||||
f"已上传发货通知文件并创建任务 {task_id}。通知原文已保存,后台已开始处理。"
|
||||
if orchestrator_started
|
||||
else f"已上传发货通知文件并创建任务 {task_id}。通知原文已保存。"
|
||||
),
|
||||
"data": {
|
||||
"task": serialize_task_summary(task) if task else {"task_no": task_id},
|
||||
"notice_upload": {"filename": upload.filename or "", **meta},
|
||||
"parse_status": "deferred",
|
||||
"orchestrator_started": orchestrator_started,
|
||||
},
|
||||
}
|
||||
return jsonify({'status': 'ok', 'task_id': task_id, 'message': f'已上传发货通知文件并创建任务 {task_id}。通知原文已保存,后台已开始处理。' if orchestrator_started else f'已上传发货通知文件并创建任务 {task_id}。通知原文已保存。', 'data': {'task': serialize_task_summary(task) if task else {'task_no': task_id}, 'notice_upload': {'filename': upload.filename or '', **meta}, 'parse_status': 'deferred', 'orchestrator_started': orchestrator_started}})
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/replace-notice', methods=['POST'])
|
||||
def workspace_replace_shipping_task_notice(task_no: str):
|
||||
"""重新上传发货通知并覆盖当前任务,不新建批次/任务。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
upload = request.files.get('file')
|
||||
if not upload:
|
||||
raise ValidationError('file is required')
|
||||
from app.services.shipping_notice import task_workflow
|
||||
from app.services.shipping_notice.notice_upload import extract_notice_text, guess_source_type, max_notice_chars, save_task_notice_upload
|
||||
raw = upload.read() or b''
|
||||
filename = upload.filename or 'notice'
|
||||
saved_path = save_task_notice_upload(task.task_no, filename, raw)
|
||||
text, meta = extract_notice_text(saved_path)
|
||||
warnings = list(meta.get('warnings') or []) if isinstance(meta, dict) else []
|
||||
if text:
|
||||
limit = max_notice_chars()
|
||||
if len(text) > limit:
|
||||
text = text[:limit]
|
||||
warnings.append(f'notice_text_truncated:{limit}')
|
||||
task.source_type = guess_source_type(filename) or task.source_type
|
||||
result = task_workflow.replace_task_notice(
|
||||
task,
|
||||
raw_text=text,
|
||||
source_file_name=filename,
|
||||
source_file_type=str(getattr(upload, 'mimetype', '') or '').strip(),
|
||||
warnings=warnings,
|
||||
)
|
||||
data = result.setdefault('data', {})
|
||||
if isinstance(data, dict):
|
||||
data['notice_upload'] = {'filename': filename, **(meta if isinstance(meta, dict) else {})}
|
||||
return jsonify(result)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>", methods=["GET"])
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>', methods=['GET'])
|
||||
def workspace_shipping_task_detail(task_no: str):
|
||||
"""返回指定任务的详情快照。"""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
return jsonify({"error": "Not found"}), 404
|
||||
raise NotFoundError('Not found')
|
||||
return jsonify(serialize_task_detail(task))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/chat-actions", methods=["GET"])
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/chat-actions', methods=['GET'])
|
||||
def workspace_shipping_task_chat_actions(task_no: str):
|
||||
"""返回聊天气泡侧所需的动作按钮与检查点信息。"""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
return jsonify({"error": "Not found"}), 404
|
||||
raise NotFoundError('Not found')
|
||||
return jsonify(build_chat_actions_payload(task))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/retry", methods=["POST"])
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/retry', methods=['POST'])
|
||||
def workspace_retry_shipping_task(task_no: str):
|
||||
"""重试当前任务,适用于超时、解析失败或自动推进中断后的恢复。"""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
return jsonify({"error": "Not found"}), 404
|
||||
|
||||
raise NotFoundError('Not found')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
|
||||
data = request.get_json(silent=True) or {}
|
||||
payload = {"task_id": task.task_no}
|
||||
comment = str(data.get("comment") or "").strip()
|
||||
payload = {'task_id': task.task_no}
|
||||
comment = str(data.get('comment') or '').strip()
|
||||
if comment:
|
||||
payload["comment"] = comment
|
||||
payload['comment'] = comment
|
||||
return jsonify(shipping_tools.retry_task(payload))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/upload-inventory", methods=["POST"])
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/upload-inventory', methods=['POST'])
|
||||
def workspace_upload_shipping_inventory(task_no: str):
|
||||
"""用户态上传库存 Excel,并在服务端完成解析。"""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
return jsonify({"error": "Not found"}), 404
|
||||
|
||||
upload = request.files.get("file")
|
||||
raise NotFoundError('Not found')
|
||||
upload = request.files.get('file')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
|
||||
return jsonify(shipping_tools.upload_inventory_file(task.task_no, upload))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/apply-inventory-mapping", methods=["POST"])
|
||||
def workspace_apply_inventory_mapping(task_no: str):
|
||||
"""提交库存字段映射,并允许在工作台侧自动回退到下一步。"""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/confirm-inventory-source', methods=['POST'])
|
||||
def workspace_confirm_shipping_inventory_source(task_no: str):
|
||||
"""确认当前任务的库存 RPA 来源,并继续触发库存导出。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
return jsonify({"error": "Not found"}), 404
|
||||
|
||||
raise NotFoundError('Not found')
|
||||
data = request.get_json(silent=True) or {}
|
||||
source_code = str(data.get('source_code') or '').strip()
|
||||
if not source_code:
|
||||
raise ValidationError('source_code is required')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
return jsonify(shipping_tools.confirm_inventory_source({'task_id': task.task_no, 'source_code': source_code}))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/apply-inventory-mapping', methods=['POST'])
|
||||
def workspace_apply_inventory_mapping(task_no: str):
|
||||
"""提交库存字段映射,并允许在工作台侧自动回退到下一步。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
data = request.get_json(silent=True) or {}
|
||||
map_json = data.get(MAP_JSON)
|
||||
if not isinstance(map_json, dict) or not map_json:
|
||||
return jsonify({"error": f"{MAP_JSON} is required"}), 400
|
||||
|
||||
raise ValidationError(f'{MAP_JSON} is required')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
|
||||
payload = {"task_id": task.task_no, MAP_JSON: map_json, AUTO_CHAIN_FALLBACK: True}
|
||||
payload = {'task_id': task.task_no, MAP_JSON: map_json, AUTO_CHAIN_FALLBACK: True}
|
||||
return jsonify(shipping_tools.apply_inventory_mapping(payload))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/submit-decision", methods=["POST"])
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/submit-decision', methods=['POST'])
|
||||
def workspace_submit_shipping_decision(task_no: str):
|
||||
"""以用户态提交人工决策,绕过 Dify Tool 路由直接驱动状态机。"""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
return jsonify({"error": "Not found"}), 404
|
||||
|
||||
raise NotFoundError('Not found')
|
||||
data = request.get_json(silent=True) or {}
|
||||
decision = str(data.get("decision") or "").strip()
|
||||
decision = str(data.get('decision') or '').strip()
|
||||
if not decision:
|
||||
return jsonify({"error": "decision is required"}), 400
|
||||
|
||||
raise ValidationError('decision is required')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
|
||||
payload = {"task_id": task.task_no, "decision": decision, AUTO_CHAIN_FALLBACK: True}
|
||||
comment = str(data.get("comment") or "").strip()
|
||||
payload = {'task_id': task.task_no, 'decision': decision, AUTO_CHAIN_FALLBACK: True}
|
||||
comment = str(data.get('comment') or '').strip()
|
||||
if comment:
|
||||
payload["comment"] = comment
|
||||
payload['comment'] = comment
|
||||
return jsonify(shipping_tools.submit_decision(payload))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/update-notice-fields", methods=["POST"])
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/update-notice-fields', methods=['POST'])
|
||||
def workspace_update_shipping_notice_fields(task_no: str):
|
||||
"""更新发货通知单头字段。"""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
return jsonify({"error": "Not found"}), 404
|
||||
|
||||
raise NotFoundError('Not found')
|
||||
data = request.get_json(silent=True) or {}
|
||||
fields = data.get("fields")
|
||||
fields = data.get('fields')
|
||||
if not isinstance(fields, dict) or not fields:
|
||||
return jsonify({"error": "fields is required"}), 400
|
||||
|
||||
raise ValidationError('fields is required')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
|
||||
payload = {"task_id": task.task_no, "fields": fields}
|
||||
comment = str(data.get("comment") or "").strip()
|
||||
payload = {'task_id': task.task_no, 'fields': fields}
|
||||
comment = str(data.get('comment') or '').strip()
|
||||
if comment:
|
||||
payload["comment"] = comment
|
||||
payload['comment'] = comment
|
||||
return jsonify(shipping_tools.update_notice_fields(payload))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/update-notice-line", methods=["POST"])
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/update-notice-line', methods=['POST'])
|
||||
def workspace_update_shipping_notice_line(task_no: str):
|
||||
"""更新发货通知中的指定订单行。"""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
return jsonify({"error": "Not found"}), 404
|
||||
|
||||
raise NotFoundError('Not found')
|
||||
data = request.get_json(silent=True) or {}
|
||||
try:
|
||||
line_index = int(data.get("line_index"))
|
||||
line_index = int(data.get('line_index'))
|
||||
except (TypeError, ValueError):
|
||||
return jsonify({"error": "line_index is required"}), 400
|
||||
patch = data.get("patch")
|
||||
raise ValidationError('line_index is required')
|
||||
patch = data.get('patch')
|
||||
if not isinstance(patch, dict) or not patch:
|
||||
return jsonify({"error": "patch is required"}), 400
|
||||
|
||||
raise ValidationError('patch is required')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
|
||||
payload = {"task_id": task.task_no, "line_index": line_index, "patch": patch}
|
||||
comment = str(data.get("comment") or "").strip()
|
||||
payload = {'task_id': task.task_no, 'line_index': line_index, 'patch': patch}
|
||||
comment = str(data.get('comment') or '').strip()
|
||||
if comment:
|
||||
payload["comment"] = comment
|
||||
payload['comment'] = comment
|
||||
return jsonify(shipping_tools.update_notice_line(payload))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/add-notice-line", methods=["POST"])
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/add-notice-line', methods=['POST'])
|
||||
def workspace_add_shipping_notice_line(task_no: str):
|
||||
"""为发货通知新增订单行。"""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
return jsonify({"error": "Not found"}), 404
|
||||
|
||||
raise NotFoundError('Not found')
|
||||
data = request.get_json(silent=True) or {}
|
||||
line = data.get("line")
|
||||
line = data.get('line')
|
||||
if not isinstance(line, dict) or not line:
|
||||
return jsonify({"error": "line is required"}), 400
|
||||
|
||||
raise ValidationError('line is required')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
|
||||
payload = {"task_id": task.task_no, "line": line}
|
||||
comment = str(data.get("comment") or "").strip()
|
||||
payload = {'task_id': task.task_no, 'line': line}
|
||||
comment = str(data.get('comment') or '').strip()
|
||||
if comment:
|
||||
payload["comment"] = comment
|
||||
payload['comment'] = comment
|
||||
return jsonify(shipping_tools.add_notice_line(payload))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/remove-notice-line", methods=["POST"])
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/remove-notice-line', methods=['POST'])
|
||||
def workspace_remove_shipping_notice_line(task_no: str):
|
||||
"""删除发货通知中的指定订单行。"""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
return jsonify({"error": "Not found"}), 404
|
||||
|
||||
raise NotFoundError('Not found')
|
||||
data = request.get_json(silent=True) or {}
|
||||
try:
|
||||
line_index = int(data.get("line_index"))
|
||||
line_index = int(data.get('line_index'))
|
||||
except (TypeError, ValueError):
|
||||
return jsonify({"error": "line_index is required"}), 400
|
||||
|
||||
raise ValidationError('line_index is required')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
|
||||
payload = {"task_id": task.task_no, "line_index": line_index}
|
||||
comment = str(data.get("comment") or "").strip()
|
||||
payload = {'task_id': task.task_no, 'line_index': line_index}
|
||||
comment = str(data.get('comment') or '').strip()
|
||||
if comment:
|
||||
payload["comment"] = comment
|
||||
payload['comment'] = comment
|
||||
return jsonify(shipping_tools.remove_notice_line(payload))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/auto-progress", methods=["POST"])
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/auto-progress', methods=['POST'])
|
||||
def workspace_auto_progress_shipping_task(task_no: str):
|
||||
"""用户态触发 auto_progress,作为聊天前端的兜底自动推进入口。"""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
return jsonify({"error": "Not found"}), 404
|
||||
|
||||
raise NotFoundError('Not found')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
|
||||
data = request.get_json(silent=True) or {}
|
||||
payload: dict = {"task_id": task.task_no}
|
||||
for key in ("lang", "locale", "language"):
|
||||
payload: dict = {'task_id': task.task_no}
|
||||
for key in ('lang', 'locale', 'language'):
|
||||
if data.get(key):
|
||||
payload[key] = data[key]
|
||||
break
|
||||
result = shipping_tools.auto_progress(payload)
|
||||
if isinstance(result, dict) and result.get("status") == "ok":
|
||||
gen_data = result.get("data")
|
||||
if isinstance(gen_data, dict) and gen_data.get("export_file_path"):
|
||||
gen_data = {**gen_data, "download_url": f"/api/workspace/shipping-tasks/{task.task_no}/export"}
|
||||
result = {**result, "data": gen_data}
|
||||
if isinstance(result, dict) and result.get('status') == 'ok':
|
||||
gen_data = result.get('data')
|
||||
if isinstance(gen_data, dict) and gen_data.get('export_file_path'):
|
||||
gen_data = {**gen_data, 'download_url': f'/api/workspace/shipping-tasks/{task.task_no}/export'}
|
||||
result = {**result, 'data': gen_data}
|
||||
return jsonify(result)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/match-inventory", methods=["POST"])
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/match-inventory', methods=['POST'])
|
||||
def workspace_match_shipping_inventory(task_no: str):
|
||||
"""执行库存匹配,并在生成 Excel 后补充前端可直接下载的链接。"""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
return jsonify({"error": "Not found"}), 404
|
||||
|
||||
raise NotFoundError('Not found')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
from app.services.shipping_notice.state_machine import (
|
||||
action_buttons_for_checkpoint,
|
||||
human_options_for_checkpoint,
|
||||
)
|
||||
|
||||
matched = shipping_tools.match_inventory({"task_id": task.task_no, AUTO_CHAIN_FALLBACK: True})
|
||||
from app.services.shipping_notice.state_machine import action_buttons_for_checkpoint, human_options_for_checkpoint
|
||||
matched = shipping_tools.match_inventory({'task_id': task.task_no, AUTO_CHAIN_FALLBACK: True})
|
||||
if not isinstance(matched, dict):
|
||||
return jsonify(matched)
|
||||
data = matched.get("data")
|
||||
if isinstance(data, dict) and data.get("export_file_path"):
|
||||
matched = {
|
||||
**matched,
|
||||
"data": {**data, "download_url": f"/api/workspace/shipping-tasks/{task.task_no}/export"},
|
||||
}
|
||||
checkpoint = matched.get("checkpoint") or CP_EXPORT_GENERATED
|
||||
if matched.get("status") == "ok" and data and data.get("export_file_path"):
|
||||
matched["checkpoint"] = checkpoint
|
||||
if "human_options" not in matched:
|
||||
data = matched.get('data')
|
||||
if isinstance(data, dict) and data.get('export_file_path'):
|
||||
matched = {**matched, 'data': {**data, 'download_url': f'/api/workspace/shipping-tasks/{task.task_no}/export'}}
|
||||
checkpoint = matched.get('checkpoint') or CP_EXPORT_GENERATED
|
||||
if matched.get('status') == 'ok' and data and data.get('export_file_path'):
|
||||
matched['checkpoint'] = checkpoint
|
||||
if 'human_options' not in matched:
|
||||
options = human_options_for_checkpoint(checkpoint)
|
||||
if options is not None:
|
||||
matched["human_options"] = options
|
||||
if "action_buttons" not in matched:
|
||||
matched['human_options'] = options
|
||||
if 'action_buttons' not in matched:
|
||||
buttons = action_buttons_for_checkpoint(checkpoint)
|
||||
if buttons:
|
||||
matched["action_buttons"] = buttons
|
||||
matched['action_buttons'] = buttons
|
||||
return jsonify(matched)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/mark-manual-uploaded", methods=["POST"])
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/mark-manual-uploaded', methods=['POST'])
|
||||
def workspace_mark_manual_uploaded(task_no: str):
|
||||
"""标记货代系统已人工上传完成,无需再等待 RPA 回执。"""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
return jsonify({"error": "Not found"}), 404
|
||||
|
||||
raise NotFoundError('Not found')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
return jsonify(shipping_tools.upload_to_freight({'task_id': task.task_no, 'mode': 'manual_confirm'}))
|
||||
|
||||
return jsonify(
|
||||
shipping_tools.upload_to_freight({"task_id": task.task_no, "mode": "manual_confirm"})
|
||||
)
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/retry-upload', methods=['POST'])
|
||||
def workspace_retry_shipping_upload(task_no: str):
|
||||
"""用户态重试上传货代系统,直接触发既有 RPA 上传链路。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
return jsonify(shipping_tools.upload_to_freight({'task_id': task.task_no, 'mode': 'retry_upload'}))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/generate-excel", methods=["POST"])
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/generate-excel', methods=['POST'])
|
||||
def workspace_generate_shipping_excel(task_no: str):
|
||||
"""为指定任务生成出货 Excel,并补充工作台下载链接。"""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
return jsonify({"error": "Not found"}), 404
|
||||
|
||||
raise NotFoundError('Not found')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
|
||||
result = shipping_tools.generate_excel({"task_id": task.task_no})
|
||||
if isinstance(result, dict) and result.get("status") == "ok":
|
||||
data = result.get("data")
|
||||
result = shipping_tools.generate_excel({'task_id': task.task_no})
|
||||
if isinstance(result, dict) and result.get('status') == 'ok':
|
||||
data = result.get('data')
|
||||
if not isinstance(data, dict):
|
||||
data = {}
|
||||
result["data"] = data
|
||||
data["download_url"] = f"/api/workspace/shipping-tasks/{task.task_no}/export"
|
||||
result['data'] = data
|
||||
data['download_url'] = f'/api/workspace/shipping-tasks/{task.task_no}/export'
|
||||
return jsonify(result)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/export", methods=["GET"])
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/export', methods=['GET'])
|
||||
def workspace_shipping_task_export(task_no: str):
|
||||
"""下载当前用户可访问任务的出货 Excel。"""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
err_msg = task_export_error_message(task)
|
||||
if err_msg:
|
||||
return jsonify({"error": err_msg}), 404
|
||||
raise NotFoundError(err_msg)
|
||||
resolved = resolve_task_export_download(task)
|
||||
assert resolved is not None
|
||||
path, download_name = resolved
|
||||
return send_file(
|
||||
path,
|
||||
as_attachment=True,
|
||||
download_name=download_name,
|
||||
mimetype=EXPORT_MIME_TYPE,
|
||||
)
|
||||
return send_file(path, as_attachment=True, download_name=download_name, mimetype=EXPORT_MIME_TYPE)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-batches/<batch_no>/retry-pending", methods=["POST"])
|
||||
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>/retry-pending', methods=['POST'])
|
||||
def workspace_retry_shipping_batch_pending(batch_no: str):
|
||||
"""重试批次中仍可自动推进的任务,跳过终态和人工阻断任务。"""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
user = _require_user()
|
||||
batch = get_batch_for_user(batch_no, user.id)
|
||||
if not batch:
|
||||
return jsonify({"error": "Not found"}), 404
|
||||
|
||||
raise NotFoundError('Not found')
|
||||
from app.services.shipping_notice.batch_orchestrator import retry_batch_pending_tasks
|
||||
|
||||
return jsonify(retry_batch_pending_tasks(batch.batch_no))
|
||||
+8
-284
@@ -1,287 +1,11 @@
|
||||
import time
|
||||
import json
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Any, Optional
|
||||
"""
|
||||
backend/app/auth_jwt.py
|
||||
|
||||
import jwt
|
||||
import requests
|
||||
from flask import current_app, g, request
|
||||
from sqlalchemy.exc import DatabaseError, OperationalError
|
||||
用途:兼容层 — 权威实现位于 app.core.auth.jwt。
|
||||
依赖:app.core.auth.jwt。
|
||||
逻辑:Casdoor JWKS 校验与 get_current_user;新代码请 from app.core.auth.jwt import ...。
|
||||
"""
|
||||
|
||||
from app import db
|
||||
from app.models import User
|
||||
from app.core.auth.jwt import get_current_user, issue_local_access_token # noqa: F401
|
||||
|
||||
_JWKS_CACHE: dict[str, Any] = {
|
||||
'url': None,
|
||||
'keys': None,
|
||||
'expires_at': 0.0,
|
||||
}
|
||||
|
||||
def _token_brief(token: Optional[str]) -> str:
|
||||
if not token:
|
||||
return 'empty'
|
||||
text = str(token)
|
||||
if len(text) <= 16:
|
||||
return f'len={len(text)}:{text}'
|
||||
return f'len={len(text)}:{text[:8]}...{text[-8:]}'
|
||||
|
||||
|
||||
def _extract_bearer_token() -> Optional[str]:
|
||||
# Only trust standard Bearer token; reject all non-Bearer auth schemes.
|
||||
auth = request.headers.get('Authorization', '')
|
||||
if not auth:
|
||||
return None
|
||||
parts = auth.split(' ', 1)
|
||||
if len(parts) != 2 or parts[0].lower() != 'bearer':
|
||||
return None
|
||||
token = parts[1].strip()
|
||||
return token or None
|
||||
|
||||
|
||||
def _get_jwks_keys(jwks_url: str) -> dict:
|
||||
# Keep a short in-memory JWKS cache to avoid hitting Casdoor for every request.
|
||||
now = time.time()
|
||||
if (
|
||||
_JWKS_CACHE.get('url') == jwks_url
|
||||
and isinstance(_JWKS_CACHE.get('keys'), dict)
|
||||
and now < float(_JWKS_CACHE.get('expires_at') or 0.0)
|
||||
):
|
||||
return _JWKS_CACHE['keys']
|
||||
|
||||
resp = requests.get(jwks_url, timeout=5)
|
||||
resp.raise_for_status()
|
||||
data = resp.json() or {}
|
||||
keys = {}
|
||||
for item in data.get('keys', []):
|
||||
kid = item.get('kid')
|
||||
if kid:
|
||||
keys[kid] = item
|
||||
if not keys:
|
||||
raise ValueError('No JWKS keys found')
|
||||
|
||||
_JWKS_CACHE['url'] = jwks_url
|
||||
_JWKS_CACHE['keys'] = keys
|
||||
_JWKS_CACHE['expires_at'] = now + 300
|
||||
return keys
|
||||
|
||||
|
||||
def _decode_jwt(token: str) -> dict:
|
||||
# Strictly validate iss/aud/exp/iat against Casdoor metadata-derived settings.
|
||||
issuer = (current_app.config.get('AUTH_JWT_ISSUER') or '').strip()
|
||||
audience = (current_app.config.get('AUTH_JWT_AUDIENCE') or '').strip()
|
||||
jwks_url = (current_app.config.get('AUTH_JWT_JWKS_URL') or '').strip()
|
||||
if not issuer or not audience or not jwks_url:
|
||||
raise ValueError('JWT auth is not fully configured')
|
||||
|
||||
header = jwt.get_unverified_header(token)
|
||||
kid = header.get('kid')
|
||||
current_app.logger.info(
|
||||
'[auth_jwt] decode start kid=%s alg=%s token=%s',
|
||||
kid,
|
||||
header.get('alg'),
|
||||
_token_brief(token),
|
||||
)
|
||||
if not kid:
|
||||
if not bool(current_app.config.get('AUTH_ALLOW_LOCAL_JWT', True)):
|
||||
raise ValueError('JWT header missing kid')
|
||||
secret = current_app.config.get('SECRET_KEY')
|
||||
if not secret:
|
||||
raise ValueError('Local JWT secret is missing')
|
||||
local_issuer = (current_app.config.get('AUTH_LOCAL_JWT_ISSUER') or 'hxops-backend').strip()
|
||||
local_audience = (current_app.config.get('AUTH_LOCAL_JWT_AUDIENCE') or 'hxops-frontend').strip()
|
||||
return jwt.decode(
|
||||
token,
|
||||
key=secret,
|
||||
algorithms=['HS256'],
|
||||
audience=local_audience,
|
||||
issuer=local_issuer,
|
||||
options={'require': ['exp', 'iat']},
|
||||
)
|
||||
|
||||
keys = _get_jwks_keys(jwks_url)
|
||||
jwk = keys.get(kid)
|
||||
if not jwk:
|
||||
# stale cache fallback
|
||||
_JWKS_CACHE['expires_at'] = 0.0
|
||||
keys = _get_jwks_keys(jwks_url)
|
||||
jwk = keys.get(kid)
|
||||
if not jwk:
|
||||
raise ValueError('No matching JWKS key for token')
|
||||
|
||||
# Different jwt packages/versions expose JWK->public-key helpers differently.
|
||||
# Try multiple compatible paths to avoid hard dependency on one symbol name.
|
||||
public_key = None
|
||||
pyjwk = getattr(jwt, 'PyJWK', None)
|
||||
if pyjwk and hasattr(pyjwk, 'from_dict'):
|
||||
public_key = pyjwk.from_dict(jwk).key
|
||||
if public_key is None:
|
||||
rsa_alg = getattr(getattr(jwt, 'algorithms', None), 'RSAAlgorithm', None)
|
||||
if rsa_alg and hasattr(rsa_alg, 'from_jwk'):
|
||||
public_key = rsa_alg.from_jwk(json.dumps(jwk))
|
||||
if public_key is None:
|
||||
get_algs = getattr(getattr(jwt, 'algorithms', None), 'get_default_algorithms', None)
|
||||
if callable(get_algs):
|
||||
rs256 = (get_algs() or {}).get('RS256')
|
||||
if rs256 and hasattr(rs256, 'from_jwk'):
|
||||
public_key = rs256.from_jwk(json.dumps(jwk))
|
||||
if public_key is None:
|
||||
raise ValueError('Cannot build RSA public key from JWK; check installed jwt package')
|
||||
|
||||
return jwt.decode(
|
||||
token,
|
||||
key=public_key,
|
||||
algorithms=['RS256', 'RS384', 'RS512'],
|
||||
audience=audience,
|
||||
issuer=issuer,
|
||||
options={'require': ['exp', 'iat']},
|
||||
)
|
||||
|
||||
|
||||
def _extract_unverified_claims(token: str) -> dict:
|
||||
"""Best-effort decode without signature verification for troubleshooting logs."""
|
||||
try:
|
||||
return jwt.decode(
|
||||
token,
|
||||
options={
|
||||
'verify_signature': False,
|
||||
'verify_exp': False,
|
||||
'verify_iat': False,
|
||||
'verify_nbf': False,
|
||||
'verify_aud': False,
|
||||
'verify_iss': False,
|
||||
},
|
||||
) or {}
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
|
||||
def _resolve_user_from_claims(claims: dict) -> Optional[User]:
|
||||
# Resolution order keeps compatibility with different token claim conventions.
|
||||
def _lookup() -> Optional[User]:
|
||||
user_id = claims.get('user_id') or claims.get('id')
|
||||
if user_id is not None:
|
||||
try:
|
||||
user = db.session.get(User, int(user_id))
|
||||
if user:
|
||||
return user
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
|
||||
username = claims.get('preferred_username') or claims.get('username') or claims.get('name')
|
||||
if username:
|
||||
user = db.session.query(User).filter_by(username=str(username)).first()
|
||||
if user:
|
||||
return user
|
||||
|
||||
email = claims.get('email')
|
||||
if email:
|
||||
user = db.session.query(User).filter_by(email=str(email)).first()
|
||||
if user:
|
||||
return user
|
||||
return None
|
||||
|
||||
try:
|
||||
return _lookup()
|
||||
except (OperationalError, DatabaseError) as exc:
|
||||
current_app.logger.warning('[auth_jwt] transient db error when resolving user, retry with reconnect path=%s err=%s', request.path, exc)
|
||||
db.session.rollback()
|
||||
db.session.remove()
|
||||
try:
|
||||
db.engine.dispose()
|
||||
except Exception:
|
||||
current_app.logger.warning('[auth_jwt] failed to dispose engine during user reconnect recovery', exc_info=True)
|
||||
return _lookup()
|
||||
|
||||
|
||||
def _legacy_header_user() -> Optional[User]:
|
||||
def _lookup() -> Optional[User]:
|
||||
user_id = request.headers.get('X-User-Id')
|
||||
if user_id:
|
||||
try:
|
||||
user = db.session.get(User, int(user_id))
|
||||
if user:
|
||||
return user
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
|
||||
username = request.headers.get('X-Username')
|
||||
if username:
|
||||
return db.session.query(User).filter_by(username=username).first()
|
||||
return None
|
||||
|
||||
try:
|
||||
return _lookup()
|
||||
except (OperationalError, DatabaseError) as exc:
|
||||
current_app.logger.warning('[auth_jwt] transient db error when resolving legacy header user, retry with reconnect path=%s err=%s', request.path, exc)
|
||||
db.session.rollback()
|
||||
db.session.remove()
|
||||
try:
|
||||
db.engine.dispose()
|
||||
except Exception:
|
||||
current_app.logger.warning('[auth_jwt] failed to dispose engine during legacy user reconnect recovery', exc_info=True)
|
||||
return _lookup()
|
||||
|
||||
|
||||
def get_current_user() -> Optional[User]:
|
||||
cached = getattr(g, 'current_user', None)
|
||||
if cached is not None:
|
||||
return cached
|
||||
|
||||
token = _extract_bearer_token()
|
||||
if token:
|
||||
try:
|
||||
claims = _decode_jwt(token)
|
||||
user = _resolve_user_from_claims(claims)
|
||||
current_app.logger.info(
|
||||
'[auth_jwt] decode ok sub=%s username=%s resolved_user=%s',
|
||||
claims.get('sub'),
|
||||
claims.get('preferred_username') or claims.get('username') or claims.get('name'),
|
||||
getattr(user, 'username', None),
|
||||
)
|
||||
except Exception:
|
||||
# Any decode/lookup failure should behave as unauthenticated.
|
||||
unverified = _extract_unverified_claims(token)
|
||||
expected_issuer = (current_app.config.get('AUTH_JWT_ISSUER') or '').strip()
|
||||
expected_audience = (current_app.config.get('AUTH_JWT_AUDIENCE') or '').strip()
|
||||
current_app.logger.error(
|
||||
'[auth_jwt] decode context token_iss=%s token_aud=%s expected_iss=%s expected_aud=%s',
|
||||
unverified.get('iss'),
|
||||
unverified.get('aud'),
|
||||
expected_issuer,
|
||||
expected_audience,
|
||||
)
|
||||
current_app.logger.exception('[auth_jwt] decode failed token=%s path=%s', _token_brief(token), request.path)
|
||||
user = None
|
||||
claims = None
|
||||
if user:
|
||||
g.jwt_claims = claims
|
||||
g.current_user = user
|
||||
return user
|
||||
|
||||
if bool(current_app.config.get('AUTH_LEGACY_HEADER_ENABLED', True)):
|
||||
user = _legacy_header_user()
|
||||
if user:
|
||||
g.current_user = user
|
||||
return user
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def issue_local_access_token(user: User) -> str:
|
||||
"""Issue local HS256 JWT for password-login flow compatibility."""
|
||||
now = datetime.now(timezone.utc)
|
||||
exp_hours = int(current_app.config.get('AUTH_LOCAL_JWT_EXPIRES_HOURS') or 12)
|
||||
payload = {
|
||||
'sub': str(user.id),
|
||||
'id': user.id,
|
||||
'user_id': user.id,
|
||||
'username': user.username,
|
||||
'role': user.role,
|
||||
'email': user.email,
|
||||
'iat': int(now.timestamp()),
|
||||
'exp': int((now + timedelta(hours=max(1, exp_hours))).timestamp()),
|
||||
'iss': (current_app.config.get('AUTH_LOCAL_JWT_ISSUER') or 'hxops-backend'),
|
||||
'aud': (current_app.config.get('AUTH_LOCAL_JWT_AUDIENCE') or 'hxops-frontend'),
|
||||
}
|
||||
secret = current_app.config.get('SECRET_KEY')
|
||||
return jwt.encode(payload, secret, algorithm='HS256')
|
||||
__all__ = ['get_current_user', 'issue_local_access_token']
|
||||
+20
-320
@@ -1,325 +1,25 @@
|
||||
"""
|
||||
backend/app/config.py
|
||||
配置类,区分开发/生产环境
|
||||
|
||||
用途:兼容层 — 权威实现位于 app.core.config.settings。
|
||||
依赖:app.core.config.settings。
|
||||
逻辑:环境文件加载与 Config 类;新代码请 from app.core.config.settings import config。
|
||||
"""
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
from dotenv import load_dotenv
|
||||
|
||||
|
||||
_BACKEND_DIR = Path(__file__).resolve().parents[1]
|
||||
_ROOT_DIR = _BACKEND_DIR.parent
|
||||
|
||||
|
||||
def _normalize_env_name(raw: str | None) -> str:
|
||||
value = (raw or '').strip().lower()
|
||||
if value in ('dev', 'development', ''):
|
||||
return 'dev'
|
||||
if value in ('test', 'testing'):
|
||||
return 'test'
|
||||
if value in ('prod', 'production'):
|
||||
return 'prod'
|
||||
return 'dev'
|
||||
|
||||
|
||||
def _load_environment_files() -> str:
|
||||
"""Load env files from project root with stable priority.
|
||||
|
||||
Priority (low -> high):
|
||||
1. .env.shared
|
||||
2. .env.<ENV_NAME>
|
||||
3. .env.local (only for dev)
|
||||
4. system environment variables (always highest, never overridden)
|
||||
"""
|
||||
env_name = _normalize_env_name(os.getenv('ENV_NAME') or os.getenv('FLASK_ENV'))
|
||||
shared_file = _ROOT_DIR / '.env.shared'
|
||||
if shared_file.exists():
|
||||
load_dotenv(shared_file, override=False)
|
||||
|
||||
env_file = _ROOT_DIR / f'.env.{env_name}'
|
||||
if env_file.exists():
|
||||
load_dotenv(env_file, override=True)
|
||||
|
||||
if env_name == 'dev':
|
||||
local_file = _ROOT_DIR / '.env.local'
|
||||
if local_file.exists():
|
||||
load_dotenv(local_file, override=True)
|
||||
return env_name
|
||||
|
||||
|
||||
ACTIVE_ENV_NAME = _load_environment_files()
|
||||
|
||||
|
||||
def _data_path(env_key: str, *parts: str) -> str:
|
||||
from app.path_utils import resolve_backend_relative_path
|
||||
|
||||
default = _BACKEND_DIR.joinpath("data", *parts)
|
||||
return resolve_backend_relative_path(os.getenv(env_key), default)
|
||||
|
||||
|
||||
def _backend_path(env_key: str, *parts: str) -> str:
|
||||
from app.path_utils import resolve_backend_relative_path
|
||||
|
||||
default = _BACKEND_DIR.joinpath(*parts)
|
||||
return resolve_backend_relative_path(os.getenv(env_key), default)
|
||||
|
||||
|
||||
class Config:
|
||||
SQLALCHEMY_TRACK_MODIFICATIONS = False
|
||||
SECRET_KEY = os.getenv('SECRET_KEY')
|
||||
KB_STORAGE_ROOT = os.getenv('KB_STORAGE_ROOT', str(_BACKEND_DIR / 'data' / 'kb'))
|
||||
KB_TASK_EXECUTION_MODE = os.getenv('KB_TASK_EXECUTION_MODE', 'worker').strip().lower()
|
||||
KB_WORKER_POLL_SECONDS = float(os.getenv('KB_WORKER_POLL_SECONDS', '2'))
|
||||
KB_WORKER_CONCURRENCY = int(os.getenv('KB_WORKER_CONCURRENCY', '3') or '3')
|
||||
# kb-worker 自动回收长时间 running 的任务(秒),默认 300,应大于单次清洗预期耗时
|
||||
KB_JOB_RUNNING_TIMEOUT_SECONDS = float(os.getenv('KB_JOB_RUNNING_TIMEOUT_SECONDS', '300'))
|
||||
# 单文件清洗总超时(秒);超时后终止当前文件处理,避免卡住整个 worker 队列
|
||||
EDKB_FILE_TIMEOUT_SEC = int(os.getenv('EDKB_FILE_TIMEOUT_SEC', '0') or '0')
|
||||
# 数据库连接池配置
|
||||
SQLALCHEMY_ENGINE_OPTIONS = {
|
||||
'pool_size': 20,
|
||||
'max_overflow': 10,
|
||||
'pool_recycle': 3600,
|
||||
'pool_pre_ping': True,
|
||||
}
|
||||
PUBLIC_BASE_URL = os.getenv('PUBLIC_BASE_URL')
|
||||
DEFAULT_ADMIN_USERNAME = os.getenv('DEFAULT_ADMIN_USERNAME')
|
||||
DEFAULT_ADMIN_PASSWORD = os.getenv('DEFAULT_ADMIN_PASSWORD')
|
||||
TASK_EXECUTION_MODE = os.getenv('TASK_EXECUTION_MODE', '').strip().lower()
|
||||
# Dify 网关配置
|
||||
DIFY_API_BASE = os.getenv('DIFY_API_BASE')
|
||||
DIFY_API_KEY = os.getenv('DIFY_API_KEY')
|
||||
DIFY_CHAT_CONNECT_TIMEOUT_SECONDS = int(os.getenv('DIFY_CHAT_CONNECT_TIMEOUT_SECONDS', '5'))
|
||||
DIFY_CHAT_READ_TIMEOUT_SECONDS = int(os.getenv('DIFY_CHAT_READ_TIMEOUT_SECONDS', '30'))
|
||||
# Redis 连接配置,默认使用本地 Redis + 密码
|
||||
REDIS_URL = os.getenv('REDIS_URL')
|
||||
FEEDBACK_ENABLED = os.getenv('FEEDBACK_ENABLED', 'true').lower() == 'true'
|
||||
HR_WORKFLOW_IFRAME_URL = os.getenv('HR_WORKFLOW_IFRAME_URL')
|
||||
HR_WORKFLOW_API_BASE = os.getenv('HR_WORKFLOW_API_BASE')
|
||||
HR_WORKFLOW_API_KEY = os.getenv('HR_WORKFLOW_API_KEY')
|
||||
OA_WORKFLOW_WSDL_URL = os.getenv(
|
||||
'OA_WORKFLOW_WSDL_URL',
|
||||
'http://oa.well-trust.com:8888/services/WorkflowService?wsdl',
|
||||
)
|
||||
OA_LEAVE_WORKFLOW_CODE = os.getenv('OA_LEAVE_WORKFLOW_CODE', '879')
|
||||
|
||||
# External integration API (resolve original source file links by Dify IDs)
|
||||
INTEGRATION_API_MODE = os.getenv('INTEGRATION_API_MODE', 'local').strip().lower()
|
||||
INTEGRATION_API_BASE = os.getenv('INTEGRATION_API_BASE')
|
||||
INTEGRATION_API_KEY = os.getenv('INTEGRATION_API_KEY')
|
||||
|
||||
# HXOPS Tool API 对外基地址(文件检核 / 货代等 Dify Chatflow 共用;无尾斜杠)
|
||||
HXOPS_TOOLS_API_BASE = os.getenv('HXOPS_TOOLS_API_BASE') or os.getenv('HXOPS_TOOLS_API_BASE')
|
||||
|
||||
# 货代发货通知 Agent Tool API
|
||||
SHIPPING_NOTICE_TOOL_API_KEY = os.getenv('SHIPPING_NOTICE_TOOL_API_KEY')
|
||||
|
||||
# 文件检核 Chatflow Tool API
|
||||
FILE_CHECK_TOOL_API_KEY = os.getenv('FILE_CHECK_TOOL_API_KEY')
|
||||
SHIPPING_NOTICE_STORAGE_ROOT = _data_path("SHIPPING_NOTICE_STORAGE_ROOT", "shipping_notice")
|
||||
SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD = float(
|
||||
os.getenv('SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD') or '0.7'
|
||||
)
|
||||
# 建单后是否延后 parse_notice,交由 Dify 画布 LLM + Tool 解析(默认 true,符合 Dify 优先原则)
|
||||
SHIPPING_NOTICE_DEFER_PARSE_TO_DIFY = os.getenv('SHIPPING_NOTICE_DEFER_PARSE_TO_DIFY', 'true').lower() == 'true'
|
||||
SHIPPING_NOTICE_BATCH_ORCHESTRATOR_ENABLED = (
|
||||
os.getenv('SHIPPING_NOTICE_BATCH_ORCHESTRATOR_ENABLED', 'true').lower() == 'true'
|
||||
)
|
||||
SHIPPING_NOTICE_BATCH_DISPATCH_CONCURRENCY = int(
|
||||
os.getenv('SHIPPING_NOTICE_BATCH_DISPATCH_CONCURRENCY') or '3'
|
||||
)
|
||||
SHIPPING_NOTICE_DIFY_PARSE_TIMEOUT_SECONDS = int(
|
||||
os.getenv('SHIPPING_NOTICE_DIFY_PARSE_TIMEOUT_SECONDS') or '180'
|
||||
)
|
||||
SHIPPING_NOTICE_TASK_EXECUTION_MODE = os.getenv('SHIPPING_NOTICE_TASK_EXECUTION_MODE', 'worker').strip().lower()
|
||||
SHIPPING_NOTICE_WORKER_POLL_SECONDS = float(os.getenv('SHIPPING_NOTICE_WORKER_POLL_SECONDS', '2'))
|
||||
SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS = float(
|
||||
os.getenv('SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS', '300')
|
||||
)
|
||||
SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW = os.getenv('SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW', 'true')
|
||||
SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED = os.getenv('SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED', 'false').lower() == 'true'
|
||||
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED = (
|
||||
os.getenv('SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED', 'true').lower() == 'true'
|
||||
)
|
||||
SHIPPING_NOTICE_RPA_INVENTORY_MAX_ATTEMPTS = int(
|
||||
os.getenv('SHIPPING_NOTICE_RPA_INVENTORY_MAX_ATTEMPTS') or '3'
|
||||
)
|
||||
SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS = int(
|
||||
os.getenv('SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS') or '120'
|
||||
)
|
||||
SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM = os.getenv('SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM', 'false').lower() == 'true'
|
||||
SHIPPING_NOTICE_AUTO_MATCH_ENABLED = os.getenv('SHIPPING_NOTICE_AUTO_MATCH_ENABLED', 'true').lower() == 'true'
|
||||
SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED = (
|
||||
os.getenv('SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED', 'true').lower() == 'true'
|
||||
)
|
||||
SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN = os.getenv(
|
||||
'SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN',
|
||||
'shipment_{task_no}_{ts}.xlsx',
|
||||
)
|
||||
SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED = os.getenv('SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED', 'false').lower() == 'true'
|
||||
# Hxops 工作台 / 聊天按钮兜底串联(Dify 主路径走 auto_progress;画布 HTTP 不传 auto_chain_fallback)
|
||||
SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK = os.getenv('SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK', 'true').lower() == 'true'
|
||||
SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS = int(os.getenv('SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS') or '3')
|
||||
SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS = int(
|
||||
os.getenv('SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS') or '30'
|
||||
)
|
||||
SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS = int(
|
||||
os.getenv('SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS') or '80000'
|
||||
)
|
||||
SHIPPING_NOTICE_AUTO_INVENTORY_CONFIDENCE = float(
|
||||
os.getenv('SHIPPING_NOTICE_AUTO_INVENTORY_CONFIDENCE') or '0.8'
|
||||
)
|
||||
SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS = os.getenv('SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS')
|
||||
FREIGHT_INVENTORY_COLUMN_MAP = os.getenv('FREIGHT_INVENTORY_COLUMN_MAP')
|
||||
FREIGHT_INVENTORY_DROP_DIR = _data_path("FREIGHT_INVENTORY_DROP_DIR", "freight_rpa", "inventory_drop")
|
||||
FREIGHT_RPA_INVENTORY_TRIGGER_DIR = _data_path(
|
||||
"FREIGHT_RPA_INVENTORY_TRIGGER_DIR", "freight_rpa", "inventory_triggers"
|
||||
)
|
||||
FREIGHT_UPLOAD_QUEUE_DIR = _data_path("FREIGHT_UPLOAD_QUEUE_DIR", "freight_rpa", "upload_queue")
|
||||
FREIGHT_RPA_UPLOAD_TRIGGER_DIR = _data_path(
|
||||
"FREIGHT_RPA_UPLOAD_TRIGGER_DIR", "freight_rpa", "upload_triggers"
|
||||
)
|
||||
FREIGHT_SHIPMENT_TEMPLATE_PATH = _backend_path(
|
||||
"FREIGHT_SHIPMENT_TEMPLATE_PATH", "templates", "freight_shipment_upload.xlsx"
|
||||
)
|
||||
|
||||
# WeCom (企业微信) 登录配置
|
||||
WECOM_ENABLED = os.getenv('WECOM_ENABLED', 'false').lower() == 'true'
|
||||
WECOM_CORP_ID = os.getenv('WECOM_CORP_ID')
|
||||
WECOM_AGENT_ID = os.getenv('WECOM_AGENT_ID')
|
||||
WECOM_SECRET = os.getenv('WECOM_SECRET')
|
||||
WECOM_REDIRECT_URI = os.getenv('WECOM_REDIRECT_URI')
|
||||
WECOM_AUTO_CREATE_USER = os.getenv('WECOM_AUTO_CREATE_USER', 'true').lower() == 'true'
|
||||
WECOM_MATCH_RULES = os.getenv('WECOM_MATCH_RULES')
|
||||
WECOM_MATCH_OPERATOR = os.getenv('WECOM_MATCH_OPERATOR').upper()
|
||||
WECOM_FIRST_LOGIN_BIND_MODE = os.getenv('WECOM_FIRST_LOGIN_BIND_MODE')
|
||||
WECOM_FIRST_LOGIN_INPUT_FIELDS = os.getenv('WECOM_FIRST_LOGIN_INPUT_FIELDS')
|
||||
WECOM_EMPLOYEE_ID_SOURCE = os.getenv('WECOM_EMPLOYEE_ID_SOURCE')
|
||||
WECOM_MOBILE_NORMALIZE = os.getenv('WECOM_MOBILE_NORMALIZE', 'true').lower() == 'true'
|
||||
WECOM_CALLBACK_TOKEN = os.getenv('WECOM_CALLBACK_TOKEN')
|
||||
WECOM_ENCODING_AES_KEY = os.getenv('WECOM_ENCODING_AES_KEY')
|
||||
WECOM_CALLBACK_URL = os.getenv('WECOM_CALLBACK_URL')
|
||||
WECOM_HOMEPAGE_URL = os.getenv('WECOM_HOMEPAGE_URL')
|
||||
WECOM_TRUSTED_DOMAIN = os.getenv('WECOM_TRUSTED_DOMAIN')
|
||||
# Public HTTPS origin for WeCom console URLs (takes priority over notify base + request host).
|
||||
WECOM_PUBLIC_BASE_URL = os.getenv('WECOM_PUBLIC_BASE_URL')
|
||||
WECOM_NOTIFY_ENABLED = os.getenv('WECOM_NOTIFY_ENABLED', 'true').lower() == 'true'
|
||||
WECOM_NOTIFY_BASE_URL = os.getenv('WECOM_NOTIFY_BASE_URL')
|
||||
WECOM_NOTIFY_EVENTS = os.getenv('WECOM_NOTIFY_EVENTS', 'task_completed,schedule_completed,password_reset')
|
||||
WECOM_FEEDBACK_NOTIFY_ENABLED = os.getenv('WECOM_FEEDBACK_NOTIFY_ENABLED', 'true').lower() == 'true'
|
||||
WECOM_FEEDBACK_NOTIFY_BASE_URL = os.getenv('WECOM_FEEDBACK_NOTIFY_BASE_URL')
|
||||
WECOM_FEEDBACK_BOT_WEBHOOK = os.getenv('WECOM_FEEDBACK_BOT_WEBHOOK')
|
||||
|
||||
# JWT/Casdoor auth configuration (phase-1 compatible rollout)
|
||||
AUTH_LEGACY_HEADER_ENABLED = os.getenv('AUTH_LEGACY_HEADER_ENABLED', 'true').lower() == 'true'
|
||||
AUTH_JWT_REQUIRED = os.getenv('AUTH_JWT_REQUIRED', 'true').lower() == 'true'
|
||||
AUTH_ALLOW_LOCAL_PASSWORD_LOGIN = os.getenv('AUTH_ALLOW_LOCAL_PASSWORD_LOGIN', 'true').lower() == 'true'
|
||||
# Login mode switch: "casdoor" (default) or "password".
|
||||
# casdoor: login form credentials are sent to Casdoor token endpoint (no redirect page for users).
|
||||
# password: keep legacy local username/password login.
|
||||
AUTH_LOGIN_MODE = os.getenv('AUTH_LOGIN_MODE').strip().lower()
|
||||
AUTH_ALLOW_LOCAL_JWT = os.getenv('AUTH_ALLOW_LOCAL_JWT', 'true').lower() == 'true'
|
||||
# JWT 的签发者(iss)校验值,后端用它确认“这个 token 是谁发的”
|
||||
AUTH_JWT_ISSUER = os.getenv('AUTH_JWT_ISSUER')
|
||||
# JWT 的受众(aud)校验值,后端用它确认“这个 token 是发给哪个应用的”
|
||||
AUTH_JWT_AUDIENCE = os.getenv('AUTH_JWT_AUDIENCE')
|
||||
# 公钥集合地址(JWKS),后端从这里拉公钥来验签 JWT
|
||||
AUTH_JWT_JWKS_URL = os.getenv('AUTH_JWT_JWKS_URL')
|
||||
CASDOOR_BASE_URL = os.getenv('CASDOOR_BASE_URL')
|
||||
CASDOOR_CLIENT_ID = os.getenv('CASDOOR_CLIENT_ID')
|
||||
CASDOOR_CLIENT_SECRET = os.getenv('CASDOOR_CLIENT_SECRET')
|
||||
# Fallback when authorize-url request omits redirect_uri; OAuth flow sends browser origin + /casdoor-callback.
|
||||
# Casdoor Application must whitelist every origin users hit, e.g. IP and domain on port 8881.
|
||||
CASDOOR_REDIRECT_URI = os.getenv('CASDOOR_REDIRECT_URI')
|
||||
CASDOOR_SCOPE = os.getenv('CASDOOR_SCOPE')
|
||||
# Casdoor organization (userOwner) for set-password and other management APIs.
|
||||
CASDOOR_ORGANIZATION = (os.getenv('CASDOOR_ORGANIZATION') or 'organization_HX').strip()
|
||||
# WeCom as Casdoor IdP: provider Name from Casdoor Providers page (used with default_provider=wecom on authorize-url).
|
||||
CASDOOR_WECOM_PROVIDER_HINT = os.getenv('CASDOOR_WECOM_PROVIDER_HINT').strip()
|
||||
CASDOOR_WECOM_SILENT_SIGNIN = os.getenv('CASDOOR_WECOM_SILENT_SIGNIN', 'false').lower() == 'true'
|
||||
AUTH_LOCAL_JWT_ISSUER = os.getenv('AUTH_LOCAL_JWT_ISSUER')
|
||||
AUTH_LOCAL_JWT_AUDIENCE = os.getenv('AUTH_LOCAL_JWT_AUDIENCE')
|
||||
AUTH_LOCAL_JWT_EXPIRES_HOURS = int(os.getenv('AUTH_LOCAL_JWT_EXPIRES_HOURS', '12'))
|
||||
SCHEDULE_WORKER_ENABLED = os.getenv('SCHEDULE_WORKER_ENABLED', 'true').lower() == 'true'
|
||||
# Cron 表达式按此时区解读(如 0 12 * * * 表示该时区 12:00);入库 next_run_at 仍为 UTC。
|
||||
SCHEDULE_TIMEZONE = (os.getenv('SCHEDULE_TIMEZONE') or 'Asia/Shanghai').strip()
|
||||
SRM_SQLSERVER_HOST = os.getenv('SRM_SQLSERVER_HOST', '')
|
||||
SRM_SQLSERVER_PORT = os.getenv('SRM_SQLSERVER_PORT', '1433')
|
||||
SRM_SQLSERVER_DATABASE = os.getenv('SRM_SQLSERVER_DATABASE', '')
|
||||
SRM_SQLSERVER_USERNAME = os.getenv('SRM_SQLSERVER_USERNAME', '')
|
||||
SRM_SQLSERVER_PASSWORD = os.getenv('SRM_SQLSERVER_PASSWORD', '')
|
||||
SRM_SQLSERVER_DRIVER = os.getenv('SRM_SQLSERVER_DRIVER', 'SQL Server')
|
||||
SRM_SQLSERVER_ENCRYPT = os.getenv('SRM_SQLSERVER_ENCRYPT', 'no')
|
||||
SRM_SQLSERVER_TRUST_CERT = os.getenv('SRM_SQLSERVER_TRUST_CERT', 'yes')
|
||||
SRM_SQLSERVER_TIMEOUT = int(os.getenv('SRM_SQLSERVER_TIMEOUT', '15'))
|
||||
SMTP_HOST = os.getenv('SMTP_HOST', '')
|
||||
SMTP_PORT = int(os.getenv('SMTP_PORT', '25'))
|
||||
SMTP_USER = os.getenv('SMTP_USER', '')
|
||||
SMTP_PASSWORD = os.getenv('SMTP_PASSWORD', '')
|
||||
SMTP_FROM = os.getenv('SMTP_FROM', '')
|
||||
SMTP_USE_TLS = os.getenv('SMTP_USE_TLS', 'true').lower() == 'true'
|
||||
INTERNAL_API_BASE_URL = os.getenv('INTERNAL_API_BASE_URL', 'http://127.0.0.1:5052')
|
||||
FIXED_ASSETS_SYNC_ENABLED = os.getenv('FIXED_ASSETS_SYNC_ENABLED', 'true').lower() == 'true'
|
||||
FIXED_ASSETS_SYNC_TIMEZONE = (os.getenv('FIXED_ASSETS_SYNC_TIMEZONE') or 'Asia/Shanghai').strip()
|
||||
FIXED_ASSETS_SYNC_HOUR = int(os.getenv('FIXED_ASSETS_SYNC_HOUR', '3') or '3')
|
||||
FIXED_ASSETS_SYNC_MINUTE = int(os.getenv('FIXED_ASSETS_SYNC_MINUTE', '0') or '0')
|
||||
FIXED_ASSETS_SYNC_TIMEOUT_SECONDS = int(os.getenv('FIXED_ASSETS_SYNC_TIMEOUT_SECONDS', '600') or '600')
|
||||
FIXED_ASSETS_SYNC_RETRY_INTERVAL_MINUTES = int(
|
||||
os.getenv('FIXED_ASSETS_SYNC_RETRY_INTERVAL_MINUTES', '30') or '30'
|
||||
)
|
||||
FIXED_ASSETS_SYNC_MAX_ATTEMPTS = int(os.getenv('FIXED_ASSETS_SYNC_MAX_ATTEMPTS', '4') or '4')
|
||||
FIXED_ASSETS_SYNC_POLL_SECONDS = int(os.getenv('FIXED_ASSETS_SYNC_POLL_SECONDS', '60') or '60')
|
||||
FIXED_ASSETS_SYNC_ON_BOOT_IF_MISSING = (
|
||||
os.getenv('FIXED_ASSETS_SYNC_ON_BOOT_IF_MISSING', 'true').lower() == 'true'
|
||||
)
|
||||
FIXED_ASSETS_HISTORY_KEEP_COUNT = int(os.getenv('FIXED_ASSETS_HISTORY_KEEP_COUNT', '3') or '3')
|
||||
FIXED_ASSETS_STORAGE_ROOT = _data_path('FIXED_ASSETS_STORAGE_ROOT', 'fixed_assets')
|
||||
FIXED_ASSETS_DOCS_EXPORT_ROOT = os.getenv(
|
||||
'FIXED_ASSETS_DOCS_EXPORT_ROOT',
|
||||
str(_ROOT_DIR / 'docs'),
|
||||
)
|
||||
FIXED_ASSETS_EXPORT_TO_DOCS = os.getenv('FIXED_ASSETS_EXPORT_TO_DOCS', 'true').lower() == 'true'
|
||||
FIXED_ASSETS_ERP_USERNAME = os.getenv('FIXED_ASSETS_ERP_USERNAME', 'EXT_VIEW_USER')
|
||||
FIXED_ASSETS_ERP_PASSWORD = os.getenv('FIXED_ASSETS_ERP_PASSWORD', 'extviewuser')
|
||||
FIXED_ASSETS_ERP_DSN = os.getenv('FIXED_ASSETS_ERP_DSN') or os.getenv('ERP_DB_DSN', '192.168.8.24:1521/topprod')
|
||||
|
||||
# MinIO 配置
|
||||
MINIO_ENDPOINT = os.getenv('MINIO_ENDPOINT', '127.0.0.1:9000')
|
||||
MINIO_ACCESS_KEY = os.getenv('MINIO_ACCESS_KEY', 'minioadmin')
|
||||
MINIO_SECRET_KEY = os.getenv('MINIO_SECRET_KEY', 'minioadmin')
|
||||
MINIO_SECURE = os.getenv('MINIO_SECURE', 'false').lower() == 'true'
|
||||
MINIO_AGENT_GUIDES_BUCKET = os.getenv('MINIO_AGENT_GUIDES_BUCKET', 'agent-guides')
|
||||
MINIO_PUBLIC_BASE_URL = os.getenv('MINIO_PUBLIC_BASE_URL', 'http://127.0.0.1:9000')
|
||||
|
||||
|
||||
class DevelopmentConfig(Config):
|
||||
DEBUG = True
|
||||
SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URL')
|
||||
|
||||
|
||||
class ProductionConfig(Config):
|
||||
DEBUG = False
|
||||
SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URL')
|
||||
|
||||
|
||||
class TestingConfig(Config):
|
||||
TESTING = True
|
||||
SQLALCHEMY_DATABASE_URI = 'sqlite:///:memory:'
|
||||
WTF_CSRF_ENABLED = False
|
||||
SQLALCHEMY_ENGINE_OPTIONS = {}
|
||||
SCHEDULE_WORKER_ENABLED = False
|
||||
FIXED_ASSETS_SYNC_ENABLED = False
|
||||
FIXED_ASSETS_EXPORT_TO_DOCS = False
|
||||
|
||||
|
||||
config = {
|
||||
'dev': DevelopmentConfig,
|
||||
'development': DevelopmentConfig,
|
||||
'test': TestingConfig,
|
||||
'testing': TestingConfig, # alias for create_app('testing') in pytest
|
||||
'prod': ProductionConfig,
|
||||
'production': ProductionConfig,
|
||||
'default': DevelopmentConfig,
|
||||
}
|
||||
from app.core.config.settings import ( # noqa: F401
|
||||
ACTIVE_ENV_NAME,
|
||||
Config,
|
||||
DevelopmentConfig,
|
||||
ProductionConfig,
|
||||
TestingConfig,
|
||||
config,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
'ACTIVE_ENV_NAME',
|
||||
'Config',
|
||||
'DevelopmentConfig',
|
||||
'ProductionConfig',
|
||||
'TestingConfig',
|
||||
'config',
|
||||
]
|
||||
@@ -1,6 +1,11 @@
|
||||
"""
|
||||
backend/app/core/__init__.py
|
||||
|
||||
用途:横切能力包入口(errors、response、auth、config、db)。
|
||||
逻辑:Wave 1 逐步将 app 根目录模块迁入 core/ 子包;过渡期旧路径 re-export。
|
||||
用途:横切能力包入口(errors、response、auth、config、decorators)。
|
||||
逻辑:业务代码优先 from app.core.errors / app.core.auth.jwt 等子模块 import;
|
||||
app/errors.py 等根路径 shim 仅作存量兼容。
|
||||
"""
|
||||
|
||||
from app.core.errors import AppError # noqa: F401
|
||||
|
||||
__all__ = ['AppError']
|
||||
@@ -1,9 +1,302 @@
|
||||
"""
|
||||
backend/app/core/auth/jwt.py
|
||||
|
||||
用途:Casdoor JWT 校验与当前用户解析(Wave 1 自 app/auth_jwt.py 迁入)。
|
||||
逻辑:api 路由与 decorators 调用 get_current_user()。
|
||||
用途:Casdoor JWT 校验、legacy header 回退与当前用户解析。
|
||||
依赖:app.extensions.db、app.models.User、PyJWT、requests。
|
||||
逻辑:api 层与 decorators 调用 get_current_user();旧路径 app.auth_jwt 为兼容 shim。
|
||||
"""
|
||||
from app.auth_jwt import get_current_user # noqa: F401
|
||||
|
||||
__all__ = ['get_current_user']
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import time
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Any, Optional
|
||||
|
||||
import jwt
|
||||
import requests
|
||||
from flask import current_app, g, request
|
||||
from sqlalchemy.exc import DatabaseError, OperationalError
|
||||
|
||||
from app.extensions import db
|
||||
from app.models import User
|
||||
|
||||
_JWKS_CACHE: dict[str, Any] = {
|
||||
'url': None,
|
||||
'keys': None,
|
||||
'expires_at': 0.0,
|
||||
}
|
||||
|
||||
|
||||
def _token_brief(token: Optional[str]) -> str:
|
||||
if not token:
|
||||
return 'empty'
|
||||
text = str(token)
|
||||
if len(text) <= 16:
|
||||
return f'len={len(text)}:{text}'
|
||||
return f'len={len(text)}:{text[:8]}...{text[-8:]}'
|
||||
|
||||
|
||||
def _extract_bearer_token() -> Optional[str]:
|
||||
auth = request.headers.get('Authorization', '')
|
||||
if not auth:
|
||||
return None
|
||||
parts = auth.split(' ', 1)
|
||||
if len(parts) != 2 or parts[0].lower() != 'bearer':
|
||||
return None
|
||||
token = parts[1].strip()
|
||||
return token or None
|
||||
|
||||
|
||||
def _get_jwks_keys(jwks_url: str) -> dict:
|
||||
now = time.time()
|
||||
if (
|
||||
_JWKS_CACHE.get('url') == jwks_url
|
||||
and isinstance(_JWKS_CACHE.get('keys'), dict)
|
||||
and now < float(_JWKS_CACHE.get('expires_at') or 0.0)
|
||||
):
|
||||
return _JWKS_CACHE['keys']
|
||||
|
||||
resp = requests.get(jwks_url, timeout=5)
|
||||
resp.raise_for_status()
|
||||
data = resp.json() or {}
|
||||
keys = {}
|
||||
for item in data.get('keys', []):
|
||||
kid = item.get('kid')
|
||||
if kid:
|
||||
keys[kid] = item
|
||||
if not keys:
|
||||
raise ValueError('No JWKS keys found')
|
||||
|
||||
_JWKS_CACHE['url'] = jwks_url
|
||||
_JWKS_CACHE['keys'] = keys
|
||||
_JWKS_CACHE['expires_at'] = now + 300
|
||||
return keys
|
||||
|
||||
|
||||
def _decode_jwt(token: str) -> dict:
|
||||
issuer = (current_app.config.get('AUTH_JWT_ISSUER') or '').strip()
|
||||
audience = (current_app.config.get('AUTH_JWT_AUDIENCE') or '').strip()
|
||||
jwks_url = (current_app.config.get('AUTH_JWT_JWKS_URL') or '').strip()
|
||||
if not issuer or not audience or not jwks_url:
|
||||
raise ValueError('JWT auth is not fully configured')
|
||||
|
||||
header = jwt.get_unverified_header(token)
|
||||
kid = header.get('kid')
|
||||
current_app.logger.info(
|
||||
'[auth_jwt] decode start kid=%s alg=%s token=%s',
|
||||
kid,
|
||||
header.get('alg'),
|
||||
_token_brief(token),
|
||||
)
|
||||
if not kid:
|
||||
if not bool(current_app.config.get('AUTH_ALLOW_LOCAL_JWT', True)):
|
||||
raise ValueError('JWT header missing kid')
|
||||
secret = current_app.config.get('SECRET_KEY')
|
||||
if not secret:
|
||||
raise ValueError('Local JWT secret is missing')
|
||||
local_issuer = (current_app.config.get('AUTH_LOCAL_JWT_ISSUER') or 'hxops-backend').strip()
|
||||
local_audience = (current_app.config.get('AUTH_LOCAL_JWT_AUDIENCE') or 'hxops-frontend').strip()
|
||||
return jwt.decode(
|
||||
token,
|
||||
key=secret,
|
||||
algorithms=['HS256'],
|
||||
audience=local_audience,
|
||||
issuer=local_issuer,
|
||||
options={'require': ['exp', 'iat']},
|
||||
)
|
||||
|
||||
keys = _get_jwks_keys(jwks_url)
|
||||
jwk = keys.get(kid)
|
||||
if not jwk:
|
||||
_JWKS_CACHE['expires_at'] = 0.0
|
||||
keys = _get_jwks_keys(jwks_url)
|
||||
jwk = keys.get(kid)
|
||||
if not jwk:
|
||||
raise ValueError('No matching JWKS key for token')
|
||||
|
||||
public_key = None
|
||||
pyjwk = getattr(jwt, 'PyJWK', None)
|
||||
if pyjwk and hasattr(pyjwk, 'from_dict'):
|
||||
public_key = pyjwk.from_dict(jwk).key
|
||||
if public_key is None:
|
||||
rsa_alg = getattr(getattr(jwt, 'algorithms', None), 'RSAAlgorithm', None)
|
||||
if rsa_alg and hasattr(rsa_alg, 'from_jwk'):
|
||||
public_key = rsa_alg.from_jwk(json.dumps(jwk))
|
||||
if public_key is None:
|
||||
get_algs = getattr(getattr(jwt, 'algorithms', None), 'get_default_algorithms', None)
|
||||
if callable(get_algs):
|
||||
rs256 = (get_algs() or {}).get('RS256')
|
||||
if rs256 and hasattr(rs256, 'from_jwk'):
|
||||
public_key = rs256.from_jwk(json.dumps(jwk))
|
||||
if public_key is None:
|
||||
raise ValueError('Cannot build RSA public key from JWK; check installed jwt package')
|
||||
|
||||
return jwt.decode(
|
||||
token,
|
||||
key=public_key,
|
||||
algorithms=['RS256', 'RS384', 'RS512'],
|
||||
audience=audience,
|
||||
issuer=issuer,
|
||||
options={'require': ['exp', 'iat']},
|
||||
)
|
||||
|
||||
|
||||
def _extract_unverified_claims(token: str) -> dict:
|
||||
try:
|
||||
return jwt.decode(
|
||||
token,
|
||||
options={
|
||||
'verify_signature': False,
|
||||
'verify_exp': False,
|
||||
'verify_iat': False,
|
||||
'verify_nbf': False,
|
||||
'verify_aud': False,
|
||||
'verify_iss': False,
|
||||
},
|
||||
) or {}
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
|
||||
def _resolve_user_from_claims(claims: dict) -> Optional[User]:
|
||||
def _lookup() -> Optional[User]:
|
||||
user_id = claims.get('user_id') or claims.get('id')
|
||||
if user_id is not None:
|
||||
try:
|
||||
user = db.session.get(User, int(user_id))
|
||||
if user:
|
||||
return user
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
|
||||
username = claims.get('preferred_username') or claims.get('username') or claims.get('name')
|
||||
if username:
|
||||
user = db.session.query(User).filter_by(username=str(username)).first()
|
||||
if user:
|
||||
return user
|
||||
|
||||
email = claims.get('email')
|
||||
if email:
|
||||
user = db.session.query(User).filter_by(email=str(email)).first()
|
||||
if user:
|
||||
return user
|
||||
return None
|
||||
|
||||
try:
|
||||
return _lookup()
|
||||
except (OperationalError, DatabaseError) as exc:
|
||||
current_app.logger.warning(
|
||||
'[auth_jwt] transient db error when resolving user, retry with reconnect path=%s err=%s',
|
||||
request.path,
|
||||
exc,
|
||||
)
|
||||
db.session.rollback()
|
||||
db.session.remove()
|
||||
try:
|
||||
db.engine.dispose()
|
||||
except Exception:
|
||||
current_app.logger.warning('[auth_jwt] failed to dispose engine during user reconnect recovery', exc_info=True)
|
||||
return _lookup()
|
||||
|
||||
|
||||
def _legacy_header_user() -> Optional[User]:
|
||||
def _lookup() -> Optional[User]:
|
||||
user_id = request.headers.get('X-User-Id')
|
||||
if user_id:
|
||||
try:
|
||||
user = db.session.get(User, int(user_id))
|
||||
if user:
|
||||
return user
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
|
||||
username = request.headers.get('X-Username')
|
||||
if username:
|
||||
return db.session.query(User).filter_by(username=username).first()
|
||||
return None
|
||||
|
||||
try:
|
||||
return _lookup()
|
||||
except (OperationalError, DatabaseError) as exc:
|
||||
current_app.logger.warning(
|
||||
'[auth_jwt] transient db error when resolving legacy header user, retry with reconnect path=%s err=%s',
|
||||
request.path,
|
||||
exc,
|
||||
)
|
||||
db.session.rollback()
|
||||
db.session.remove()
|
||||
try:
|
||||
db.engine.dispose()
|
||||
except Exception:
|
||||
current_app.logger.warning('[auth_jwt] failed to dispose engine during legacy user reconnect recovery', exc_info=True)
|
||||
return _lookup()
|
||||
|
||||
|
||||
def get_current_user() -> Optional[User]:
|
||||
"""
|
||||
解析当前请求用户:优先 JWT Bearer,其次 legacy header(若配置启用)。
|
||||
Returns:
|
||||
User 实例;未认证时返回 None。
|
||||
"""
|
||||
cached = getattr(g, 'current_user', None)
|
||||
if cached is not None:
|
||||
return cached
|
||||
|
||||
token = _extract_bearer_token()
|
||||
if token:
|
||||
try:
|
||||
claims = _decode_jwt(token)
|
||||
user = _resolve_user_from_claims(claims)
|
||||
current_app.logger.info(
|
||||
'[auth_jwt] decode ok sub=%s username=%s resolved_user=%s',
|
||||
claims.get('sub'),
|
||||
claims.get('preferred_username') or claims.get('username') or claims.get('name'),
|
||||
getattr(user, 'username', None),
|
||||
)
|
||||
except Exception:
|
||||
unverified = _extract_unverified_claims(token)
|
||||
expected_issuer = (current_app.config.get('AUTH_JWT_ISSUER') or '').strip()
|
||||
expected_audience = (current_app.config.get('AUTH_JWT_AUDIENCE') or '').strip()
|
||||
current_app.logger.error(
|
||||
'[auth_jwt] decode context token_iss=%s token_aud=%s expected_iss=%s expected_aud=%s',
|
||||
unverified.get('iss'),
|
||||
unverified.get('aud'),
|
||||
expected_issuer,
|
||||
expected_audience,
|
||||
)
|
||||
current_app.logger.exception('[auth_jwt] decode failed token=%s path=%s', _token_brief(token), request.path)
|
||||
user = None
|
||||
claims = None
|
||||
if user:
|
||||
g.jwt_claims = claims
|
||||
g.current_user = user
|
||||
return user
|
||||
|
||||
if bool(current_app.config.get('AUTH_LEGACY_HEADER_ENABLED', True)):
|
||||
user = _legacy_header_user()
|
||||
if user:
|
||||
g.current_user = user
|
||||
return user
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def issue_local_access_token(user: User) -> str:
|
||||
"""签发本地 HS256 JWT(密码登录兼容)。"""
|
||||
now = datetime.now(timezone.utc)
|
||||
exp_hours = int(current_app.config.get('AUTH_LOCAL_JWT_EXPIRES_HOURS') or 12)
|
||||
payload = {
|
||||
'sub': str(user.id),
|
||||
'id': user.id,
|
||||
'user_id': user.id,
|
||||
'username': user.username,
|
||||
'role': user.role,
|
||||
'email': user.email,
|
||||
'iat': int(now.timestamp()),
|
||||
'exp': int((now + timedelta(hours=max(1, exp_hours))).timestamp()),
|
||||
'iss': (current_app.config.get('AUTH_LOCAL_JWT_ISSUER') or 'hxops-backend'),
|
||||
'aud': (current_app.config.get('AUTH_LOCAL_JWT_AUDIENCE') or 'hxops-frontend'),
|
||||
}
|
||||
secret = current_app.config.get('SECRET_KEY')
|
||||
return jwt.encode(payload, secret, algorithm='HS256')
|
||||
@@ -1,6 +1,5 @@
|
||||
"""
|
||||
backend/app/core/config/__init__.py
|
||||
|
||||
用途:应用配置包入口(settings、env_persistence)。
|
||||
逻辑:create_app 加载 Config;before_request 刷新 DB 持久化配置。
|
||||
用途:配置包入口(settings、env_persistence)。
|
||||
"""
|
||||
@@ -1,9 +1,249 @@
|
||||
"""
|
||||
backend/app/core/config/env_persistence.py
|
||||
|
||||
用途:DB 持久化运行时配置(Wave 1 自 app/env_persistence.py 迁入)。
|
||||
逻辑:before_request 调用 apply_env_settings 刷新 app.config。
|
||||
"""
|
||||
from app.env_persistence import apply_env_settings # noqa: F401
|
||||
用途:运行时配置 DB 持久化与 env 镜像(WeCom 等 admin 设置)。
|
||||
依赖:app.extensions.db、app.models.AppSetting。
|
||||
逻辑:before_request 调用 apply_env_settings;persist_env_settings 供 admin 写入。
|
||||
|
||||
__all__ = ['apply_env_settings']
|
||||
Storage strategy:
|
||||
1. Database (app_settings) - canonical
|
||||
2. .env.local (dev only) - secondary mirror
|
||||
3. os.environ - in-process mirror on write
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import Iterable
|
||||
|
||||
from dotenv import dotenv_values, set_key
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
_BACKEND_DIR = Path(__file__).resolve().parents[3]
|
||||
_ROOT_DIR = _BACKEND_DIR.parent
|
||||
ROOT_ENV_LOCAL_PATH = _ROOT_DIR / '.env.local'
|
||||
LEGACY_BACKEND_ENV_PATH = _BACKEND_DIR / '.env'
|
||||
# Backward-compatible alias for tests and older callers that still patch/read
|
||||
# the historical backend/.env location directly.
|
||||
BACKEND_ENV_PATH = LEGACY_BACKEND_ENV_PATH
|
||||
WECOM_BOOL_KEYS = {
|
||||
'WECOM_ENABLED',
|
||||
'WECOM_AUTO_CREATE_USER',
|
||||
'WECOM_MOBILE_NORMALIZE',
|
||||
'WECOM_NOTIFY_ENABLED',
|
||||
'WECOM_FEEDBACK_NOTIFY_ENABLED',
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _ensure_env_file_exists() -> bool:
|
||||
try:
|
||||
ROOT_ENV_LOCAL_PATH.parent.mkdir(parents=True, exist_ok=True)
|
||||
if not ROOT_ENV_LOCAL_PATH.exists():
|
||||
ROOT_ENV_LOCAL_PATH.write_text('', encoding='utf-8')
|
||||
return True
|
||||
except OSError as exc:
|
||||
logger.warning('Cannot create %s: %s', ROOT_ENV_LOCAL_PATH, exc)
|
||||
return False
|
||||
|
||||
|
||||
def _normalize_env_name(raw: str | None) -> str:
|
||||
value = (raw or '').strip().lower()
|
||||
if value in ('dev', 'development', ''):
|
||||
return 'dev'
|
||||
if value in ('test', 'testing'):
|
||||
return 'test'
|
||||
if value in ('prod', 'production'):
|
||||
return 'prod'
|
||||
return 'dev'
|
||||
|
||||
|
||||
def _to_env_string(value: object) -> str:
|
||||
if isinstance(value, bool):
|
||||
return 'true' if value else 'false'
|
||||
if value is None:
|
||||
return ''
|
||||
return str(value)
|
||||
|
||||
|
||||
def _parse_env_value(key: str, value: object) -> object:
|
||||
if value is None:
|
||||
return None
|
||||
if key in WECOM_BOOL_KEYS:
|
||||
return str(value).strip().lower() == 'true'
|
||||
return str(value)
|
||||
|
||||
|
||||
def _matches_prefixes(key: str, prefixes: Iterable[str]) -> bool:
|
||||
return any(key.startswith(prefix) for prefix in prefixes)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Database read/write (primary store)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _persist_to_db(values: dict[str, str]) -> bool:
|
||||
"""Write key/value pairs into the ``app_settings`` table.
|
||||
|
||||
Returns True if every value was committed, False otherwise. The function
|
||||
is defensive: it must not raise, because settings persistence is also
|
||||
written to ``.env`` and we don't want to fail the API request.
|
||||
"""
|
||||
if not values:
|
||||
return True
|
||||
try:
|
||||
from app.extensions import db
|
||||
from app.models import AppSetting
|
||||
except Exception as exc: # pragma: no cover - import safety net
|
||||
logger.warning('AppSetting model unavailable: %s', exc)
|
||||
return False
|
||||
|
||||
try:
|
||||
for key, value in values.items():
|
||||
existing = db.session.get(AppSetting, key)
|
||||
if existing is None:
|
||||
db.session.add(AppSetting(key=key, value=value))
|
||||
else:
|
||||
existing.value = value
|
||||
db.session.commit()
|
||||
return True
|
||||
except Exception as exc:
|
||||
logger.warning('Failed to persist settings to DB: %s', exc)
|
||||
try:
|
||||
db.session.rollback()
|
||||
except Exception: # pragma: no cover
|
||||
pass
|
||||
return False
|
||||
|
||||
|
||||
def _load_from_db(prefixes: tuple[str, ...]) -> dict[str, str]:
|
||||
try:
|
||||
from app.extensions import db
|
||||
from app.models import AppSetting
|
||||
except Exception as exc: # pragma: no cover
|
||||
logger.debug('AppSetting model unavailable for read: %s', exc)
|
||||
return {}
|
||||
|
||||
try:
|
||||
rows = db.session.query(AppSetting).all()
|
||||
except Exception as exc:
|
||||
# Most common case: the migration has not been applied yet on a
|
||||
# freshly-built container. Degrade gracefully to .env-only mode.
|
||||
logger.debug('app_settings table not readable yet: %s', exc)
|
||||
try:
|
||||
db.session.rollback()
|
||||
except Exception: # pragma: no cover
|
||||
pass
|
||||
return {}
|
||||
|
||||
result: dict[str, str] = {}
|
||||
for row in rows:
|
||||
if row.key and _matches_prefixes(row.key, prefixes):
|
||||
result[row.key] = row.value if row.value is not None else ''
|
||||
return result
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# .env read/write (secondary store, best-effort)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _persist_to_env_file(values: dict[str, str]) -> bool:
|
||||
env_name = _normalize_env_name(os.getenv('ENV_NAME') or os.getenv('FLASK_ENV'))
|
||||
if env_name != 'dev':
|
||||
return True
|
||||
if not values:
|
||||
return True
|
||||
if not _ensure_env_file_exists():
|
||||
return False
|
||||
ok = True
|
||||
for key, value in values.items():
|
||||
try:
|
||||
set_key(str(ROOT_ENV_LOCAL_PATH), key, value, quote_mode='auto')
|
||||
except OSError as exc:
|
||||
logger.warning('Cannot write %s to %s: %s', key, ROOT_ENV_LOCAL_PATH, exc)
|
||||
ok = False
|
||||
return ok
|
||||
|
||||
|
||||
def _load_from_env_file(prefixes: tuple[str, ...]) -> dict[str, str]:
|
||||
merged: dict[str, str] = {}
|
||||
for env_path in (BACKEND_ENV_PATH, ROOT_ENV_LOCAL_PATH):
|
||||
if not env_path.exists():
|
||||
continue
|
||||
try:
|
||||
loaded = dotenv_values(env_path)
|
||||
except OSError as exc:
|
||||
logger.warning('Cannot read %s: %s', env_path, exc)
|
||||
continue
|
||||
for key, value in loaded.items():
|
||||
if key and _matches_prefixes(key, prefixes):
|
||||
merged[key] = value if value is not None else ''
|
||||
return merged
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Public API
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def persist_env_settings(values: dict[str, object]) -> dict[str, str]:
|
||||
"""Persist settings to the canonical store and mirror to ``os.environ``.
|
||||
|
||||
Order:
|
||||
1. Mirror to ``os.environ`` so the current process picks them up
|
||||
immediately.
|
||||
2. Persist to the database (canonical, survives container rebuilds).
|
||||
3. In dev only, best-effort write to ``.env.local`` so local restarts
|
||||
without DB access keep working.
|
||||
"""
|
||||
if not values:
|
||||
return {}
|
||||
|
||||
persisted: dict[str, str] = {}
|
||||
for key, value in values.items():
|
||||
env_value = _to_env_string(value)
|
||||
os.environ[key] = env_value
|
||||
persisted[key] = env_value
|
||||
|
||||
db_ok = _persist_to_db(persisted)
|
||||
file_ok = _persist_to_env_file(persisted)
|
||||
|
||||
if not db_ok and not file_ok:
|
||||
logger.error(
|
||||
'Failed to persist settings %s to BOTH database and .env.local mirror. '
|
||||
'Settings will be lost when the process restarts.',
|
||||
list(persisted.keys()),
|
||||
)
|
||||
|
||||
return persisted
|
||||
|
||||
|
||||
def apply_env_settings(prefixes: tuple[str, ...] = ('WECOM_',)) -> dict[str, object]:
|
||||
"""Load settings from the canonical store and apply to ``os.environ``.
|
||||
|
||||
DB values take priority over env-file values; both are merged so
|
||||
keys that only live in env files (e.g. fresh deploy before any admin
|
||||
edit) are still honored.
|
||||
"""
|
||||
file_values = _load_from_env_file(prefixes)
|
||||
db_values = _load_from_db(prefixes)
|
||||
|
||||
merged: dict[str, str] = {**file_values, **db_values}
|
||||
|
||||
applied: dict[str, object] = {}
|
||||
for key, raw_value in merged.items():
|
||||
parsed = _parse_env_value(key, raw_value)
|
||||
os.environ[key] = _to_env_string(parsed)
|
||||
applied[key] = parsed
|
||||
return applied
|
||||
@@ -1,9 +1,332 @@
|
||||
"""
|
||||
backend/app/core/config/settings.py
|
||||
|
||||
用途:Config 类与环境映射(Wave 1 自 app/config.py 迁入)。
|
||||
逻辑:create_app(config_name) 通过 config[config_name] 加载。
|
||||
用途:Flask Config 类与环境文件加载(dev/test/prod)。
|
||||
依赖:dotenv、app.path_utils。
|
||||
逻辑:create_app 通过 config[config_name] 加载;旧路径 app.config 为兼容 shim。
|
||||
"""
|
||||
from app.config import ACTIVE_ENV_NAME, config # noqa: F401
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
from dotenv import load_dotenv
|
||||
|
||||
|
||||
_BACKEND_DIR = Path(__file__).resolve().parents[3]
|
||||
_ROOT_DIR = _BACKEND_DIR.parent
|
||||
|
||||
|
||||
def _normalize_env_name(raw: str | None) -> str:
|
||||
value = (raw or '').strip().lower()
|
||||
if value in ('dev', 'development', ''):
|
||||
return 'dev'
|
||||
if value in ('test', 'testing'):
|
||||
return 'test'
|
||||
if value in ('prod', 'production'):
|
||||
return 'prod'
|
||||
return 'dev'
|
||||
|
||||
|
||||
def _load_environment_files() -> str:
|
||||
"""Load env files from project root with stable priority.
|
||||
|
||||
Priority (low -> high):
|
||||
1. .env.shared
|
||||
2. .env.<ENV_NAME>
|
||||
3. .env.local (only for dev)
|
||||
4. system environment variables (always highest, never overridden)
|
||||
"""
|
||||
env_name = _normalize_env_name(os.getenv('ENV_NAME') or os.getenv('FLASK_ENV'))
|
||||
shared_file = _ROOT_DIR / '.env.shared'
|
||||
if shared_file.exists():
|
||||
load_dotenv(shared_file, override=False)
|
||||
|
||||
env_file = _ROOT_DIR / f'.env.{env_name}'
|
||||
if env_file.exists():
|
||||
load_dotenv(env_file, override=True)
|
||||
|
||||
if env_name == 'dev':
|
||||
local_file = _ROOT_DIR / '.env.local'
|
||||
if local_file.exists():
|
||||
load_dotenv(local_file, override=True)
|
||||
return env_name
|
||||
|
||||
|
||||
ACTIVE_ENV_NAME = _load_environment_files()
|
||||
|
||||
|
||||
def _data_path(env_key: str, *parts: str) -> str:
|
||||
from app.path_utils import resolve_backend_relative_path
|
||||
|
||||
default = _BACKEND_DIR.joinpath("data", *parts)
|
||||
return resolve_backend_relative_path(os.getenv(env_key), default)
|
||||
|
||||
|
||||
def _backend_path(env_key: str, *parts: str) -> str:
|
||||
from app.path_utils import resolve_backend_relative_path
|
||||
|
||||
default = _BACKEND_DIR.joinpath(*parts)
|
||||
return resolve_backend_relative_path(os.getenv(env_key), default)
|
||||
|
||||
|
||||
class Config:
|
||||
SQLALCHEMY_TRACK_MODIFICATIONS = False
|
||||
SECRET_KEY = os.getenv('SECRET_KEY')
|
||||
KB_STORAGE_ROOT = _data_path('KB_STORAGE_ROOT', 'kb')
|
||||
KB_TASK_EXECUTION_MODE = os.getenv('KB_TASK_EXECUTION_MODE', 'worker').strip().lower()
|
||||
KB_WORKER_POLL_SECONDS = float(os.getenv('KB_WORKER_POLL_SECONDS', '2'))
|
||||
KB_WORKER_CONCURRENCY = int(os.getenv('KB_WORKER_CONCURRENCY', '3') or '3')
|
||||
# kb-worker 自动回收长时间 running 的任务(秒),默认 300,应大于单次清洗预期耗时
|
||||
KB_JOB_RUNNING_TIMEOUT_SECONDS = float(os.getenv('KB_JOB_RUNNING_TIMEOUT_SECONDS', '300'))
|
||||
# 单文件清洗总超时(秒);超时后终止当前文件处理,避免卡住整个 worker 队列
|
||||
EDKB_FILE_TIMEOUT_SEC = int(os.getenv('EDKB_FILE_TIMEOUT_SEC', '0') or '0')
|
||||
# 数据库连接池配置
|
||||
SQLALCHEMY_ENGINE_OPTIONS = {
|
||||
'pool_size': 20,
|
||||
'max_overflow': 10,
|
||||
'pool_recycle': 3600,
|
||||
'pool_pre_ping': True,
|
||||
}
|
||||
PUBLIC_BASE_URL = os.getenv('PUBLIC_BASE_URL')
|
||||
DEFAULT_ADMIN_USERNAME = os.getenv('DEFAULT_ADMIN_USERNAME')
|
||||
DEFAULT_ADMIN_PASSWORD = os.getenv('DEFAULT_ADMIN_PASSWORD')
|
||||
TASK_EXECUTION_MODE = os.getenv('TASK_EXECUTION_MODE', '').strip().lower()
|
||||
# Dify 网关配置
|
||||
DIFY_API_BASE = os.getenv('DIFY_API_BASE')
|
||||
DIFY_API_KEY = os.getenv('DIFY_API_KEY')
|
||||
DIFY_CHAT_CONNECT_TIMEOUT_SECONDS = int(os.getenv('DIFY_CHAT_CONNECT_TIMEOUT_SECONDS', '5'))
|
||||
DIFY_CHAT_READ_TIMEOUT_SECONDS = int(os.getenv('DIFY_CHAT_READ_TIMEOUT_SECONDS', '30'))
|
||||
# Redis 连接配置,默认使用本地 Redis + 密码
|
||||
REDIS_URL = os.getenv('REDIS_URL')
|
||||
FEEDBACK_ENABLED = os.getenv('FEEDBACK_ENABLED', 'true').lower() == 'true'
|
||||
HR_WORKFLOW_IFRAME_URL = os.getenv('HR_WORKFLOW_IFRAME_URL')
|
||||
HR_WORKFLOW_API_BASE = os.getenv('HR_WORKFLOW_API_BASE')
|
||||
HR_WORKFLOW_API_KEY = os.getenv('HR_WORKFLOW_API_KEY')
|
||||
OA_WORKFLOW_WSDL_URL = os.getenv(
|
||||
'OA_WORKFLOW_WSDL_URL',
|
||||
'http://oa.well-trust.com:8888/services/WorkflowService?wsdl',
|
||||
)
|
||||
OA_LEAVE_WORKFLOW_CODE = os.getenv('OA_LEAVE_WORKFLOW_CODE', '879')
|
||||
|
||||
# External integration API (resolve original source file links by Dify IDs)
|
||||
INTEGRATION_API_MODE = os.getenv('INTEGRATION_API_MODE', 'local').strip().lower()
|
||||
INTEGRATION_API_BASE = os.getenv('INTEGRATION_API_BASE')
|
||||
INTEGRATION_API_KEY = os.getenv('INTEGRATION_API_KEY')
|
||||
|
||||
# HXOPS Tool API 对外基地址(文件检核 / 货代等 Dify Chatflow 共用;无尾斜杠)
|
||||
HXOPS_TOOLS_API_BASE = os.getenv('HXOPS_TOOLS_API_BASE') or os.getenv('HXOPS_TOOLS_API_BASE')
|
||||
|
||||
# 货代发货通知 Agent Tool API
|
||||
SHIPPING_NOTICE_TOOL_API_KEY = os.getenv('SHIPPING_NOTICE_TOOL_API_KEY')
|
||||
|
||||
# 文件检核 Chatflow Tool API
|
||||
FILE_CHECK_TOOL_API_KEY = os.getenv('FILE_CHECK_TOOL_API_KEY')
|
||||
SHIPPING_NOTICE_STORAGE_ROOT = _data_path("SHIPPING_NOTICE_STORAGE_ROOT", "shipping_notice")
|
||||
SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD = float(
|
||||
os.getenv('SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD') or '0.7'
|
||||
)
|
||||
# 建单后是否延后 parse_notice,交由 Dify 画布 LLM + Tool 解析(默认 true,符合 Dify 优先原则)
|
||||
SHIPPING_NOTICE_DEFER_PARSE_TO_DIFY = os.getenv('SHIPPING_NOTICE_DEFER_PARSE_TO_DIFY', 'true').lower() == 'true'
|
||||
SHIPPING_NOTICE_BATCH_ORCHESTRATOR_ENABLED = (
|
||||
os.getenv('SHIPPING_NOTICE_BATCH_ORCHESTRATOR_ENABLED', 'true').lower() == 'true'
|
||||
)
|
||||
SHIPPING_NOTICE_BATCH_DISPATCH_CONCURRENCY = int(
|
||||
os.getenv('SHIPPING_NOTICE_BATCH_DISPATCH_CONCURRENCY') or '3'
|
||||
)
|
||||
SHIPPING_NOTICE_DIFY_PARSE_TIMEOUT_SECONDS = int(
|
||||
os.getenv('SHIPPING_NOTICE_DIFY_PARSE_TIMEOUT_SECONDS') or '180'
|
||||
)
|
||||
SHIPPING_NOTICE_TASK_EXECUTION_MODE = os.getenv('SHIPPING_NOTICE_TASK_EXECUTION_MODE', 'worker').strip().lower()
|
||||
SHIPPING_NOTICE_WORKER_POLL_SECONDS = float(os.getenv('SHIPPING_NOTICE_WORKER_POLL_SECONDS', '2'))
|
||||
SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS = float(
|
||||
os.getenv('SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS', '300')
|
||||
)
|
||||
SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW = os.getenv('SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW', 'true')
|
||||
SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED = os.getenv('SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED', 'false').lower() == 'true'
|
||||
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED = (
|
||||
os.getenv('SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED', 'true').lower() == 'true'
|
||||
)
|
||||
SHIPPING_NOTICE_RPA_INVENTORY_MAX_ATTEMPTS = int(
|
||||
os.getenv('SHIPPING_NOTICE_RPA_INVENTORY_MAX_ATTEMPTS') or '1'
|
||||
)
|
||||
SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS = int(
|
||||
os.getenv('SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS') or '120'
|
||||
)
|
||||
SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM = os.getenv('SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM', 'false').lower() == 'true'
|
||||
SHIPPING_NOTICE_AUTO_MATCH_ENABLED = os.getenv('SHIPPING_NOTICE_AUTO_MATCH_ENABLED', 'true').lower() == 'true'
|
||||
SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED = (
|
||||
os.getenv('SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED', 'true').lower() == 'true'
|
||||
)
|
||||
SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN = os.getenv(
|
||||
'SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN',
|
||||
'shipment_{task_no}_{ts}.xlsx',
|
||||
)
|
||||
SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED = os.getenv('SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED', 'false').lower() == 'true'
|
||||
# Hxops 工作台 / 聊天按钮兜底串联(Dify 主路径走 auto_progress;画布 HTTP 不传 auto_chain_fallback)
|
||||
SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK = os.getenv('SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK', 'true').lower() == 'true'
|
||||
SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS = int(os.getenv('SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS') or '3')
|
||||
SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS = int(
|
||||
os.getenv('SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS') or '30'
|
||||
)
|
||||
SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS = int(
|
||||
os.getenv('SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS') or '80000'
|
||||
)
|
||||
SHIPPING_NOTICE_AUTO_INVENTORY_CONFIDENCE = float(
|
||||
os.getenv('SHIPPING_NOTICE_AUTO_INVENTORY_CONFIDENCE') or '0.8'
|
||||
)
|
||||
SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS = os.getenv('SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS')
|
||||
FREIGHT_INVENTORY_COLUMN_MAP = os.getenv('FREIGHT_INVENTORY_COLUMN_MAP')
|
||||
FREIGHT_INVENTORY_DROP_DIR = _data_path(
|
||||
"FREIGHT_INVENTORY_DROP_DIR", "shipping_notice", "freight_rpa", "inventory_drop"
|
||||
)
|
||||
FREIGHT_RPA_INVENTORY_TRIGGER_DIR = _data_path(
|
||||
"FREIGHT_RPA_INVENTORY_TRIGGER_DIR", "shipping_notice", "freight_rpa", "inventory_triggers"
|
||||
)
|
||||
FREIGHT_UPLOAD_QUEUE_DIR = _data_path(
|
||||
"FREIGHT_UPLOAD_QUEUE_DIR", "shipping_notice", "freight_rpa", "upload_queue"
|
||||
)
|
||||
FREIGHT_RPA_UPLOAD_TRIGGER_DIR = _data_path(
|
||||
"FREIGHT_RPA_UPLOAD_TRIGGER_DIR", "shipping_notice", "freight_rpa", "upload_triggers"
|
||||
)
|
||||
FREIGHT_SHIPMENT_TEMPLATE_PATH = _backend_path(
|
||||
"FREIGHT_SHIPMENT_TEMPLATE_PATH", "templates", "freight_shipment_upload.xlsx"
|
||||
)
|
||||
|
||||
# WeCom (企业微信) 登录配置
|
||||
WECOM_ENABLED = os.getenv('WECOM_ENABLED', 'false').lower() == 'true'
|
||||
WECOM_CORP_ID = os.getenv('WECOM_CORP_ID')
|
||||
WECOM_AGENT_ID = os.getenv('WECOM_AGENT_ID')
|
||||
WECOM_SECRET = os.getenv('WECOM_SECRET')
|
||||
WECOM_REDIRECT_URI = os.getenv('WECOM_REDIRECT_URI')
|
||||
WECOM_AUTO_CREATE_USER = os.getenv('WECOM_AUTO_CREATE_USER', 'true').lower() == 'true'
|
||||
WECOM_MATCH_RULES = os.getenv('WECOM_MATCH_RULES')
|
||||
WECOM_MATCH_OPERATOR = os.getenv('WECOM_MATCH_OPERATOR').upper()
|
||||
WECOM_FIRST_LOGIN_BIND_MODE = os.getenv('WECOM_FIRST_LOGIN_BIND_MODE')
|
||||
WECOM_FIRST_LOGIN_INPUT_FIELDS = os.getenv('WECOM_FIRST_LOGIN_INPUT_FIELDS')
|
||||
WECOM_EMPLOYEE_ID_SOURCE = os.getenv('WECOM_EMPLOYEE_ID_SOURCE')
|
||||
WECOM_MOBILE_NORMALIZE = os.getenv('WECOM_MOBILE_NORMALIZE', 'true').lower() == 'true'
|
||||
WECOM_CALLBACK_TOKEN = os.getenv('WECOM_CALLBACK_TOKEN')
|
||||
WECOM_ENCODING_AES_KEY = os.getenv('WECOM_ENCODING_AES_KEY')
|
||||
WECOM_CALLBACK_URL = os.getenv('WECOM_CALLBACK_URL')
|
||||
WECOM_HOMEPAGE_URL = os.getenv('WECOM_HOMEPAGE_URL')
|
||||
WECOM_TRUSTED_DOMAIN = os.getenv('WECOM_TRUSTED_DOMAIN')
|
||||
# Public HTTPS origin for WeCom console URLs (takes priority over notify base + request host).
|
||||
WECOM_PUBLIC_BASE_URL = os.getenv('WECOM_PUBLIC_BASE_URL')
|
||||
WECOM_NOTIFY_ENABLED = os.getenv('WECOM_NOTIFY_ENABLED', 'true').lower() == 'true'
|
||||
WECOM_NOTIFY_BASE_URL = os.getenv('WECOM_NOTIFY_BASE_URL')
|
||||
WECOM_NOTIFY_EVENTS = os.getenv('WECOM_NOTIFY_EVENTS', 'task_completed,schedule_completed,password_reset')
|
||||
WECOM_FEEDBACK_NOTIFY_ENABLED = os.getenv('WECOM_FEEDBACK_NOTIFY_ENABLED', 'true').lower() == 'true'
|
||||
WECOM_FEEDBACK_NOTIFY_BASE_URL = os.getenv('WECOM_FEEDBACK_NOTIFY_BASE_URL')
|
||||
WECOM_FEEDBACK_BOT_WEBHOOK = os.getenv('WECOM_FEEDBACK_BOT_WEBHOOK')
|
||||
|
||||
# JWT/Casdoor auth configuration (phase-1 compatible rollout)
|
||||
AUTH_LEGACY_HEADER_ENABLED = os.getenv('AUTH_LEGACY_HEADER_ENABLED', 'true').lower() == 'true'
|
||||
AUTH_JWT_REQUIRED = os.getenv('AUTH_JWT_REQUIRED', 'true').lower() == 'true'
|
||||
AUTH_ALLOW_LOCAL_PASSWORD_LOGIN = os.getenv('AUTH_ALLOW_LOCAL_PASSWORD_LOGIN', 'true').lower() == 'true'
|
||||
# Login mode switch: "casdoor" (default) or "password".
|
||||
# casdoor: login form credentials are sent to Casdoor token endpoint (no redirect page for users).
|
||||
# password: keep legacy local username/password login.
|
||||
AUTH_LOGIN_MODE = os.getenv('AUTH_LOGIN_MODE').strip().lower()
|
||||
AUTH_ALLOW_LOCAL_JWT = os.getenv('AUTH_ALLOW_LOCAL_JWT', 'true').lower() == 'true'
|
||||
# JWT 的签发者(iss)校验值,后端用它确认“这个 token 是谁发的”
|
||||
AUTH_JWT_ISSUER = os.getenv('AUTH_JWT_ISSUER')
|
||||
# JWT 的受众(aud)校验值,后端用它确认“这个 token 是发给哪个应用的”
|
||||
AUTH_JWT_AUDIENCE = os.getenv('AUTH_JWT_AUDIENCE')
|
||||
# 公钥集合地址(JWKS),后端从这里拉公钥来验签 JWT
|
||||
AUTH_JWT_JWKS_URL = os.getenv('AUTH_JWT_JWKS_URL')
|
||||
CASDOOR_BASE_URL = os.getenv('CASDOOR_BASE_URL')
|
||||
CASDOOR_CLIENT_ID = os.getenv('CASDOOR_CLIENT_ID')
|
||||
CASDOOR_CLIENT_SECRET = os.getenv('CASDOOR_CLIENT_SECRET')
|
||||
# Fallback when authorize-url request omits redirect_uri; OAuth flow sends browser origin + /casdoor-callback.
|
||||
# Casdoor Application must whitelist every origin users hit, e.g. IP and domain on port 8881.
|
||||
CASDOOR_REDIRECT_URI = os.getenv('CASDOOR_REDIRECT_URI')
|
||||
CASDOOR_SCOPE = os.getenv('CASDOOR_SCOPE')
|
||||
# Casdoor organization (userOwner) for set-password and other management APIs.
|
||||
CASDOOR_ORGANIZATION = (os.getenv('CASDOOR_ORGANIZATION') or 'organization_HX').strip()
|
||||
# WeCom as Casdoor IdP: provider Name from Casdoor Providers page (used with default_provider=wecom on authorize-url).
|
||||
CASDOOR_WECOM_PROVIDER_HINT = os.getenv('CASDOOR_WECOM_PROVIDER_HINT').strip()
|
||||
CASDOOR_WECOM_SILENT_SIGNIN = os.getenv('CASDOOR_WECOM_SILENT_SIGNIN', 'false').lower() == 'true'
|
||||
AUTH_LOCAL_JWT_ISSUER = os.getenv('AUTH_LOCAL_JWT_ISSUER')
|
||||
AUTH_LOCAL_JWT_AUDIENCE = os.getenv('AUTH_LOCAL_JWT_AUDIENCE')
|
||||
AUTH_LOCAL_JWT_EXPIRES_HOURS = int(os.getenv('AUTH_LOCAL_JWT_EXPIRES_HOURS', '12'))
|
||||
SCHEDULE_WORKER_ENABLED = os.getenv('SCHEDULE_WORKER_ENABLED', 'true').lower() == 'true'
|
||||
# Cron 表达式按此时区解读(如 0 12 * * * 表示该时区 12:00);入库 next_run_at 仍为 UTC。
|
||||
SCHEDULE_TIMEZONE = (os.getenv('SCHEDULE_TIMEZONE') or 'Asia/Shanghai').strip()
|
||||
SRM_SQLSERVER_HOST = os.getenv('SRM_SQLSERVER_HOST', '')
|
||||
SRM_SQLSERVER_PORT = os.getenv('SRM_SQLSERVER_PORT', '1433')
|
||||
SRM_SQLSERVER_DATABASE = os.getenv('SRM_SQLSERVER_DATABASE', '')
|
||||
SRM_SQLSERVER_USERNAME = os.getenv('SRM_SQLSERVER_USERNAME', '')
|
||||
SRM_SQLSERVER_PASSWORD = os.getenv('SRM_SQLSERVER_PASSWORD', '')
|
||||
SRM_SQLSERVER_DRIVER = os.getenv('SRM_SQLSERVER_DRIVER', 'SQL Server')
|
||||
SRM_SQLSERVER_ENCRYPT = os.getenv('SRM_SQLSERVER_ENCRYPT', 'no')
|
||||
SRM_SQLSERVER_TRUST_CERT = os.getenv('SRM_SQLSERVER_TRUST_CERT', 'yes')
|
||||
SRM_SQLSERVER_TIMEOUT = int(os.getenv('SRM_SQLSERVER_TIMEOUT', '15'))
|
||||
SMTP_HOST = os.getenv('SMTP_HOST', '')
|
||||
SMTP_PORT = int(os.getenv('SMTP_PORT', '25'))
|
||||
SMTP_USER = os.getenv('SMTP_USER', '')
|
||||
SMTP_PASSWORD = os.getenv('SMTP_PASSWORD', '')
|
||||
SMTP_FROM = os.getenv('SMTP_FROM', '')
|
||||
SMTP_USE_TLS = os.getenv('SMTP_USE_TLS', 'true').lower() == 'true'
|
||||
INTERNAL_API_BASE_URL = os.getenv('INTERNAL_API_BASE_URL', 'http://127.0.0.1:5052')
|
||||
FIXED_ASSETS_SYNC_ENABLED = os.getenv('FIXED_ASSETS_SYNC_ENABLED', 'true').lower() == 'true'
|
||||
FIXED_ASSETS_SYNC_TIMEZONE = (os.getenv('FIXED_ASSETS_SYNC_TIMEZONE') or 'Asia/Shanghai').strip()
|
||||
FIXED_ASSETS_SYNC_HOUR = int(os.getenv('FIXED_ASSETS_SYNC_HOUR', '3') or '3')
|
||||
FIXED_ASSETS_SYNC_MINUTE = int(os.getenv('FIXED_ASSETS_SYNC_MINUTE', '0') or '0')
|
||||
FIXED_ASSETS_SYNC_TIMEOUT_SECONDS = int(os.getenv('FIXED_ASSETS_SYNC_TIMEOUT_SECONDS', '600') or '600')
|
||||
FIXED_ASSETS_SYNC_RETRY_INTERVAL_MINUTES = int(
|
||||
os.getenv('FIXED_ASSETS_SYNC_RETRY_INTERVAL_MINUTES', '30') or '30'
|
||||
)
|
||||
FIXED_ASSETS_SYNC_MAX_ATTEMPTS = int(os.getenv('FIXED_ASSETS_SYNC_MAX_ATTEMPTS', '4') or '4')
|
||||
FIXED_ASSETS_SYNC_POLL_SECONDS = int(os.getenv('FIXED_ASSETS_SYNC_POLL_SECONDS', '60') or '60')
|
||||
FIXED_ASSETS_SYNC_ON_BOOT_IF_MISSING = (
|
||||
os.getenv('FIXED_ASSETS_SYNC_ON_BOOT_IF_MISSING', 'true').lower() == 'true'
|
||||
)
|
||||
FIXED_ASSETS_HISTORY_KEEP_COUNT = int(os.getenv('FIXED_ASSETS_HISTORY_KEEP_COUNT', '3') or '3')
|
||||
FIXED_ASSETS_STORAGE_ROOT = _data_path('FIXED_ASSETS_STORAGE_ROOT', 'fixed_assets')
|
||||
FIXED_ASSETS_DOCS_EXPORT_ROOT = os.getenv(
|
||||
'FIXED_ASSETS_DOCS_EXPORT_ROOT',
|
||||
str(_ROOT_DIR / 'docs'),
|
||||
)
|
||||
FIXED_ASSETS_EXPORT_TO_DOCS = os.getenv('FIXED_ASSETS_EXPORT_TO_DOCS', 'true').lower() == 'true'
|
||||
FIXED_ASSETS_ERP_USERNAME = os.getenv('FIXED_ASSETS_ERP_USERNAME', 'EXT_VIEW_USER')
|
||||
FIXED_ASSETS_ERP_PASSWORD = os.getenv('FIXED_ASSETS_ERP_PASSWORD', 'extviewuser')
|
||||
FIXED_ASSETS_ERP_DSN = os.getenv('FIXED_ASSETS_ERP_DSN') or os.getenv('ERP_DB_DSN', '192.168.8.24:1521/topprod')
|
||||
|
||||
# MinIO 配置
|
||||
MINIO_ENDPOINT = os.getenv('MINIO_ENDPOINT', '127.0.0.1:9000')
|
||||
MINIO_ACCESS_KEY = os.getenv('MINIO_ACCESS_KEY', 'minioadmin')
|
||||
MINIO_SECRET_KEY = os.getenv('MINIO_SECRET_KEY', 'minioadmin')
|
||||
MINIO_SECURE = os.getenv('MINIO_SECURE', 'false').lower() == 'true'
|
||||
MINIO_AGENT_GUIDES_BUCKET = os.getenv('MINIO_AGENT_GUIDES_BUCKET', 'agent-guides')
|
||||
MINIO_PUBLIC_BASE_URL = os.getenv('MINIO_PUBLIC_BASE_URL', 'http://127.0.0.1:9000')
|
||||
|
||||
|
||||
class DevelopmentConfig(Config):
|
||||
DEBUG = True
|
||||
SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URL')
|
||||
|
||||
|
||||
class ProductionConfig(Config):
|
||||
DEBUG = False
|
||||
SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URL')
|
||||
|
||||
|
||||
class TestingConfig(Config):
|
||||
TESTING = True
|
||||
SQLALCHEMY_DATABASE_URI = 'sqlite:///:memory:'
|
||||
WTF_CSRF_ENABLED = False
|
||||
SQLALCHEMY_ENGINE_OPTIONS = {}
|
||||
SCHEDULE_WORKER_ENABLED = False
|
||||
FIXED_ASSETS_SYNC_ENABLED = False
|
||||
FIXED_ASSETS_EXPORT_TO_DOCS = False
|
||||
|
||||
|
||||
config = {
|
||||
'dev': DevelopmentConfig,
|
||||
'development': DevelopmentConfig,
|
||||
'test': TestingConfig,
|
||||
'testing': TestingConfig, # alias for create_app('testing') in pytest
|
||||
'prod': ProductionConfig,
|
||||
'production': ProductionConfig,
|
||||
'default': DevelopmentConfig,
|
||||
}
|
||||
|
||||
__all__ = ['config', 'ACTIVE_ENV_NAME']
|
||||
@@ -1,9 +1,77 @@
|
||||
"""
|
||||
backend/app/core/decorators.py
|
||||
|
||||
用途:路由权限装饰器(Wave 1 自 app/decorators.py 迁入)。
|
||||
逻辑:api 层路由使用 @require_admin、@require_agent_permission。
|
||||
用途:API 路由权限装饰器(admin、agent 权限)。
|
||||
依赖:app.core.auth.jwt、app.core.errors、app.models。
|
||||
逻辑:api 路由使用 @require_admin、@require_agent_permission;旧路径 app.decorators 为兼容 shim。
|
||||
"""
|
||||
from app.decorators import require_admin, require_agent_permission # noqa: F401
|
||||
|
||||
__all__ = ['require_admin', 'require_agent_permission']
|
||||
from __future__ import annotations
|
||||
|
||||
from functools import wraps
|
||||
|
||||
from flask import current_app, g, request
|
||||
|
||||
from app.core.auth.jwt import get_current_user as _auth_current_user
|
||||
from app.core.errors import ForbiddenError, NotFoundError, UnauthorizedError, ValidationError
|
||||
from app.models import Agent, User
|
||||
|
||||
|
||||
def _get_current_user() -> User:
|
||||
"""通过 JWT / legacy header 解析当前用户并写入 g.current_user。"""
|
||||
user = _auth_current_user()
|
||||
if user:
|
||||
g.current_user = user
|
||||
return user
|
||||
|
||||
|
||||
def require_agent_permission(f):
|
||||
"""
|
||||
装饰器:校验当前用户是否拥有指定 Agent 访问权限。
|
||||
核心逻辑:从 body/query 读 agent_id → 获取用户 → admin 放行或检查 user.agents。
|
||||
Args:
|
||||
f: 被装饰的视图函数。
|
||||
Returns:
|
||||
包装后的视图函数。
|
||||
"""
|
||||
|
||||
@wraps(f)
|
||||
def decorated_function(*args, **kwargs):
|
||||
data = request.get_json(silent=True) or {}
|
||||
agent_id = data.get('agent_id') or request.args.get('agent_id')
|
||||
if not agent_id:
|
||||
raise ValidationError('agent_id is required')
|
||||
user = _get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
agent = Agent.query.get(agent_id)
|
||||
if not agent:
|
||||
raise NotFoundError('Agent not found')
|
||||
g.current_agent = agent
|
||||
if user.role == 'admin':
|
||||
return f(*args, **kwargs)
|
||||
if agent not in user.agents:
|
||||
raise ForbiddenError('Permission denied for this agent')
|
||||
return f(*args, **kwargs)
|
||||
|
||||
return decorated_function
|
||||
|
||||
|
||||
def require_admin(f):
|
||||
"""
|
||||
装饰器:限制仅 admin 角色可访问。
|
||||
核心逻辑:解析用户 → 校验 role == admin;JWT 必填时检查 Authorization 头。
|
||||
"""
|
||||
|
||||
@wraps(f)
|
||||
def decorated_function(*args, **kwargs):
|
||||
user = _get_current_user()
|
||||
if not user:
|
||||
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':
|
||||
raise ForbiddenError('Admin privilege required')
|
||||
return f(*args, **kwargs)
|
||||
|
||||
return decorated_function
|
||||
+99
-20
@@ -1,26 +1,105 @@
|
||||
"""
|
||||
backend/app/core/errors.py
|
||||
|
||||
用途:统一业务异常类型(Wave 1 自 app/errors.py 迁入)。
|
||||
用途:定义后端统一业务异常类型,供全局异常处理器识别并输出标准错误响应。
|
||||
依赖:无 Flask 依赖。
|
||||
逻辑:API 全局 handler 识别 AppError;业务层 raise 子类替代 jsonify(error)。
|
||||
逻辑:业务层 raise AppError 子类;create_app 注册全局 handler;旧路径 app.errors 为兼容 shim。
|
||||
"""
|
||||
from app.errors import ( # noqa: F401 — Wave 1: 实现迁入本文件后删除 app/errors.py shim
|
||||
AppError,
|
||||
ConflictError,
|
||||
ForbiddenError,
|
||||
NotFoundError,
|
||||
ServiceUnavailableError,
|
||||
UnauthorizedError,
|
||||
ValidationError,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
'AppError',
|
||||
'ValidationError',
|
||||
'UnauthorizedError',
|
||||
'ForbiddenError',
|
||||
'NotFoundError',
|
||||
'ConflictError',
|
||||
'ServiceUnavailableError',
|
||||
]
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
|
||||
|
||||
@dataclass
|
||||
class AppError(Exception):
|
||||
code: str
|
||||
message: str
|
||||
http_status: int = 400
|
||||
details: dict[str, Any] = field(default_factory=dict)
|
||||
retryable: bool = False
|
||||
|
||||
|
||||
class ValidationError(AppError):
|
||||
def __init__(self, message: str = "Invalid request parameters", *, details: dict[str, Any] | None = None):
|
||||
super().__init__(
|
||||
code="VALIDATION.INVALID_PARAM",
|
||||
message=message,
|
||||
http_status=400,
|
||||
details=details or {},
|
||||
retryable=False,
|
||||
)
|
||||
|
||||
|
||||
class UnauthorizedError(AppError):
|
||||
def __init__(self, message: str = "Unauthorized"):
|
||||
super().__init__(code="AUTH.UNAUTHORIZED", message=message, http_status=401, retryable=False)
|
||||
|
||||
|
||||
class ForbiddenError(AppError):
|
||||
def __init__(self, message: str = "Forbidden"):
|
||||
super().__init__(code="AUTH.FORBIDDEN", message=message, http_status=403, retryable=False)
|
||||
|
||||
|
||||
class NotFoundError(AppError):
|
||||
def __init__(self, message: str = "Resource not found"):
|
||||
super().__init__(code="RESOURCE.NOT_FOUND", message=message, http_status=404, retryable=False)
|
||||
|
||||
|
||||
class ConflictError(AppError):
|
||||
def __init__(
|
||||
self,
|
||||
message: str = "Resource conflict",
|
||||
*,
|
||||
code: str = "RESOURCE.CONFLICT",
|
||||
details: dict[str, Any] | None = None,
|
||||
):
|
||||
super().__init__(
|
||||
code=code,
|
||||
message=message,
|
||||
http_status=409,
|
||||
details=details or {},
|
||||
retryable=False,
|
||||
)
|
||||
|
||||
|
||||
class ServiceUnavailableError(AppError):
|
||||
def __init__(self, message: str = "Service unavailable", *, code: str = "SYSTEM.SERVICE_UNAVAILABLE"):
|
||||
super().__init__(code=code, message=message, http_status=503, retryable=True)
|
||||
|
||||
|
||||
def raise_for_status(message: str, status: int, *, code: str | None = None, details: dict[str, Any] | None = None) -> None:
|
||||
"""
|
||||
按 HTTP 状态码映射并抛出对应 AppError 子类。
|
||||
Args:
|
||||
message: 错误文案。
|
||||
status: HTTP 状态码。
|
||||
code: 可选业务错误码。
|
||||
details: 可选详情 dict。
|
||||
Raises:
|
||||
AppError 或其子类。
|
||||
"""
|
||||
if status == 401:
|
||||
raise UnauthorizedError(message)
|
||||
if status == 403:
|
||||
raise ForbiddenError(message)
|
||||
if status == 404:
|
||||
raise NotFoundError(message)
|
||||
if status == 409:
|
||||
raise ConflictError(message, code=code or "RESOURCE.CONFLICT", details=details)
|
||||
if status == 503:
|
||||
raise ServiceUnavailableError(message, code=code or "SYSTEM.SERVICE_UNAVAILABLE")
|
||||
if status >= 500:
|
||||
raise AppError(
|
||||
code=code or "SYSTEM.INTERNAL_ERROR",
|
||||
message=message,
|
||||
http_status=status,
|
||||
details=details or {},
|
||||
)
|
||||
raise AppError(
|
||||
code=code or "VALIDATION.INVALID_PARAM",
|
||||
message=message,
|
||||
http_status=status,
|
||||
details=details or {},
|
||||
)
|
||||
@@ -1,9 +1,88 @@
|
||||
"""
|
||||
backend/app/core/response.py
|
||||
|
||||
用途:统一 API 响应工具(Wave 1 自 app/response_utils.py 迁入)。
|
||||
逻辑:error_payload 供全局异常 handler 使用;ok() 供成功 envelope(可选)。
|
||||
用途:统一 API 响应结构工具(成功 envelope 与错误 payload)。
|
||||
依赖:flask.jsonify(仅 ok() 使用)。
|
||||
逻辑:create_app 异常 handler 使用 error_payload;可选 ENABLE_API_ENVELOPE 包装成功响应。
|
||||
"""
|
||||
from app.response_utils import error_payload, ok, utc_iso_now # noqa: F401
|
||||
|
||||
__all__ = ['error_payload', 'ok', 'utc_iso_now']
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
from flask import jsonify
|
||||
|
||||
|
||||
def utc_iso_now() -> str:
|
||||
"""返回当前 UTC 时间的 ISO8601 字符串(Z 后缀)。"""
|
||||
return datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
|
||||
|
||||
|
||||
def utc_iso(dt: datetime | None) -> str | None:
|
||||
"""
|
||||
将 naive UTC datetime 序列化为带 Z 后缀的 ISO 字符串。
|
||||
Args:
|
||||
dt: datetime 或 None。
|
||||
Returns:
|
||||
ISO 字符串或 None。
|
||||
"""
|
||||
if dt is None:
|
||||
return None
|
||||
if dt.tzinfo is not None:
|
||||
return dt.astimezone(timezone.utc).replace(tzinfo=None).isoformat() + "Z"
|
||||
return dt.isoformat() + "Z"
|
||||
|
||||
|
||||
def ok(data: Any, *, request_id: str | None = None, status: int = 200):
|
||||
"""
|
||||
构造 success=true 的标准 JSON 响应。
|
||||
Args:
|
||||
data: 业务数据。
|
||||
request_id: 可选请求追踪 id。
|
||||
status: HTTP 状态码。
|
||||
Returns:
|
||||
(jsonify Response, status) 元组。
|
||||
"""
|
||||
payload: dict[str, Any] = {
|
||||
"success": True,
|
||||
"data": data,
|
||||
"timestamp": utc_iso_now(),
|
||||
}
|
||||
if request_id:
|
||||
payload["request_id"] = request_id
|
||||
return jsonify(payload), status
|
||||
|
||||
|
||||
def error_payload(
|
||||
*,
|
||||
code: str,
|
||||
message: str,
|
||||
request_id: str | None = None,
|
||||
details: dict[str, Any] | None = None,
|
||||
retryable: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
构造 success=false 的错误响应体 dict(供 jsonify 使用)。
|
||||
Args:
|
||||
code: 业务错误码。
|
||||
message: 用户可见文案。
|
||||
request_id: 可选请求 id。
|
||||
details: 可选详情。
|
||||
retryable: 是否可重试。
|
||||
Returns:
|
||||
可 jsonify 的 dict。
|
||||
"""
|
||||
payload: dict[str, Any] = {
|
||||
"success": False,
|
||||
"error": {
|
||||
"code": code,
|
||||
"message": message,
|
||||
"details": details or {},
|
||||
"retryable": retryable,
|
||||
},
|
||||
"timestamp": utc_iso_now(),
|
||||
}
|
||||
if request_id:
|
||||
payload["request_id"] = request_id
|
||||
return payload
|
||||
+10
-67
@@ -1,72 +1,15 @@
|
||||
"""
|
||||
backend/app/decorators.py
|
||||
文件用途:权限控制装饰器集合
|
||||
引用文件:flask, functools, models, db
|
||||
逻辑关系:为需要鉴权的 API 提供统一的用户获取、权限校验入口
|
||||
|
||||
用途:兼容层 — 权威实现位于 app.core.decorators。
|
||||
依赖:app.core.decorators。
|
||||
逻辑:@require_admin / @require_agent_permission;新代码请 from app.core.decorators import ...。
|
||||
"""
|
||||
from functools import wraps
|
||||
from flask import request, jsonify, g, current_app
|
||||
from app.models import Agent, User
|
||||
from app.auth_jwt import get_current_user as _auth_current_user
|
||||
from app.errors import AppError, ValidationError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, ServiceUnavailableError, raise_for_status
|
||||
|
||||
def _get_current_user() -> User:
|
||||
"""Resolve current user via JWT auth flow (legacy headers optional via config)."""
|
||||
user = _auth_current_user()
|
||||
if user:
|
||||
g.current_user = user
|
||||
return user
|
||||
from app.core.decorators import ( # noqa: F401
|
||||
_get_current_user,
|
||||
require_admin,
|
||||
require_agent_permission,
|
||||
)
|
||||
|
||||
def require_agent_permission(f):
|
||||
"""
|
||||
装饰器:检查当前用户是否有指定 Agent 的访问权限
|
||||
核心逻辑:
|
||||
1. 从请求体中读取 agent_id
|
||||
2. 获取当前用户 (临时固定为 ID=1)
|
||||
3. 如果用户是 admin,则放行
|
||||
4. 否则检查 user.agents 是否包含该 agent
|
||||
传入参数:
|
||||
f: 被装饰的视图函数
|
||||
返回值:
|
||||
包装后的视图函数
|
||||
"""
|
||||
|
||||
@wraps(f)
|
||||
def decorated_function(*args, **kwargs):
|
||||
data = request.get_json(silent=True) or {}
|
||||
agent_id = data.get('agent_id') or request.args.get('agent_id')
|
||||
if not agent_id:
|
||||
raise ValidationError('agent_id is required')
|
||||
user = _get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
agent = Agent.query.get(agent_id)
|
||||
if not agent:
|
||||
raise NotFoundError('Agent not found')
|
||||
g.current_agent = agent
|
||||
if user.role == 'admin':
|
||||
return f(*args, **kwargs)
|
||||
if agent not in user.agents:
|
||||
raise ForbiddenError('Permission denied for this agent')
|
||||
return f(*args, **kwargs)
|
||||
return decorated_function
|
||||
|
||||
def require_admin(f):
|
||||
"""
|
||||
装饰器:限制只有管理员角色才能访问的接口
|
||||
核心逻辑:
|
||||
1. 获取当前用户
|
||||
2. 判断 user.role 是否为 'admin'
|
||||
"""
|
||||
|
||||
@wraps(f)
|
||||
def decorated_function(*args, **kwargs):
|
||||
user = _get_current_user()
|
||||
if not user:
|
||||
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':
|
||||
raise ForbiddenError('Admin privilege required')
|
||||
return f(*args, **kwargs)
|
||||
return decorated_function
|
||||
__all__ = ['require_admin', 'require_agent_permission', '_get_current_user']
|
||||
+19
-251
@@ -1,255 +1,23 @@
|
||||
"""Persistent storage for runtime-editable application settings.
|
||||
"""
|
||||
backend/app/env_persistence.py
|
||||
|
||||
Settings managed from the admin console (e.g. WeCom configuration) need to
|
||||
survive process restarts AND container/image rebuilds in production. Writing
|
||||
only to ``backend/.env`` is not enough on Docker deployments because the
|
||||
container's writable layer is discarded on every ``docker compose up --build``.
|
||||
|
||||
Storage strategy:
|
||||
|
||||
1. Database (``app_settings`` table) - canonical, always authoritative.
|
||||
2. ``.env.local`` (dev only) - best-effort secondary write so local/dev
|
||||
workflows that restart without DB access still see updates.
|
||||
3. ``os.environ`` - mirrored on write so legacy ``os.getenv`` consumers stay
|
||||
in sync within the running process.
|
||||
|
||||
On read we merge env files (lowest priority) over DB (highest priority); the DB
|
||||
value wins whenever it exists.
|
||||
用途:兼容层 — 权威实现位于 app.core.config.env_persistence。
|
||||
依赖:app.core.config.env_persistence。
|
||||
逻辑:WeCom 等运行时配置 DB 持久化;create_app before_request 调用 apply_env_settings。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
from app.core.config.env_persistence import ( # noqa: F401
|
||||
BACKEND_ENV_PATH,
|
||||
LEGACY_BACKEND_ENV_PATH,
|
||||
ROOT_ENV_LOCAL_PATH,
|
||||
apply_env_settings,
|
||||
persist_env_settings,
|
||||
)
|
||||
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import Iterable
|
||||
|
||||
from dotenv import dotenv_values, set_key
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
_BACKEND_DIR = Path(__file__).resolve().parents[1]
|
||||
_ROOT_DIR = _BACKEND_DIR.parent
|
||||
ROOT_ENV_LOCAL_PATH = _ROOT_DIR / '.env.local'
|
||||
LEGACY_BACKEND_ENV_PATH = _BACKEND_DIR / '.env'
|
||||
# Backward-compatible alias for tests and older callers that still patch/read
|
||||
# the historical backend/.env location directly.
|
||||
BACKEND_ENV_PATH = LEGACY_BACKEND_ENV_PATH
|
||||
WECOM_BOOL_KEYS = {
|
||||
'WECOM_ENABLED',
|
||||
'WECOM_AUTO_CREATE_USER',
|
||||
'WECOM_MOBILE_NORMALIZE',
|
||||
'WECOM_NOTIFY_ENABLED',
|
||||
'WECOM_FEEDBACK_NOTIFY_ENABLED',
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _ensure_env_file_exists() -> bool:
|
||||
try:
|
||||
ROOT_ENV_LOCAL_PATH.parent.mkdir(parents=True, exist_ok=True)
|
||||
if not ROOT_ENV_LOCAL_PATH.exists():
|
||||
ROOT_ENV_LOCAL_PATH.write_text('', encoding='utf-8')
|
||||
return True
|
||||
except OSError as exc:
|
||||
logger.warning('Cannot create %s: %s', ROOT_ENV_LOCAL_PATH, exc)
|
||||
return False
|
||||
|
||||
|
||||
def _normalize_env_name(raw: str | None) -> str:
|
||||
value = (raw or '').strip().lower()
|
||||
if value in ('dev', 'development', ''):
|
||||
return 'dev'
|
||||
if value in ('test', 'testing'):
|
||||
return 'test'
|
||||
if value in ('prod', 'production'):
|
||||
return 'prod'
|
||||
return 'dev'
|
||||
|
||||
|
||||
def _to_env_string(value: object) -> str:
|
||||
if isinstance(value, bool):
|
||||
return 'true' if value else 'false'
|
||||
if value is None:
|
||||
return ''
|
||||
return str(value)
|
||||
|
||||
|
||||
def _parse_env_value(key: str, value: object) -> object:
|
||||
if value is None:
|
||||
return None
|
||||
if key in WECOM_BOOL_KEYS:
|
||||
return str(value).strip().lower() == 'true'
|
||||
return str(value)
|
||||
|
||||
|
||||
def _matches_prefixes(key: str, prefixes: Iterable[str]) -> bool:
|
||||
return any(key.startswith(prefix) for prefix in prefixes)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Database read/write (primary store)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _persist_to_db(values: dict[str, str]) -> bool:
|
||||
"""Write key/value pairs into the ``app_settings`` table.
|
||||
|
||||
Returns True if every value was committed, False otherwise. The function
|
||||
is defensive: it must not raise, because settings persistence is also
|
||||
written to ``.env`` and we don't want to fail the API request.
|
||||
"""
|
||||
if not values:
|
||||
return True
|
||||
try:
|
||||
from app import db
|
||||
from app.models import AppSetting
|
||||
except Exception as exc: # pragma: no cover - import safety net
|
||||
logger.warning('AppSetting model unavailable: %s', exc)
|
||||
return False
|
||||
|
||||
try:
|
||||
for key, value in values.items():
|
||||
existing = db.session.get(AppSetting, key)
|
||||
if existing is None:
|
||||
db.session.add(AppSetting(key=key, value=value))
|
||||
else:
|
||||
existing.value = value
|
||||
db.session.commit()
|
||||
return True
|
||||
except Exception as exc:
|
||||
logger.warning('Failed to persist settings to DB: %s', exc)
|
||||
try:
|
||||
db.session.rollback()
|
||||
except Exception: # pragma: no cover
|
||||
pass
|
||||
return False
|
||||
|
||||
|
||||
def _load_from_db(prefixes: tuple[str, ...]) -> dict[str, str]:
|
||||
try:
|
||||
from app import db
|
||||
from app.models import AppSetting
|
||||
except Exception as exc: # pragma: no cover
|
||||
logger.debug('AppSetting model unavailable for read: %s', exc)
|
||||
return {}
|
||||
|
||||
try:
|
||||
rows = db.session.query(AppSetting).all()
|
||||
except Exception as exc:
|
||||
# Most common case: the migration has not been applied yet on a
|
||||
# freshly-built container. Degrade gracefully to .env-only mode.
|
||||
logger.debug('app_settings table not readable yet: %s', exc)
|
||||
try:
|
||||
db.session.rollback()
|
||||
except Exception: # pragma: no cover
|
||||
pass
|
||||
return {}
|
||||
|
||||
result: dict[str, str] = {}
|
||||
for row in rows:
|
||||
if row.key and _matches_prefixes(row.key, prefixes):
|
||||
result[row.key] = row.value if row.value is not None else ''
|
||||
return result
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# .env read/write (secondary store, best-effort)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _persist_to_env_file(values: dict[str, str]) -> bool:
|
||||
env_name = _normalize_env_name(os.getenv('ENV_NAME') or os.getenv('FLASK_ENV'))
|
||||
if env_name != 'dev':
|
||||
return True
|
||||
if not values:
|
||||
return True
|
||||
if not _ensure_env_file_exists():
|
||||
return False
|
||||
ok = True
|
||||
for key, value in values.items():
|
||||
try:
|
||||
set_key(str(ROOT_ENV_LOCAL_PATH), key, value, quote_mode='auto')
|
||||
except OSError as exc:
|
||||
logger.warning('Cannot write %s to %s: %s', key, ROOT_ENV_LOCAL_PATH, exc)
|
||||
ok = False
|
||||
return ok
|
||||
|
||||
|
||||
def _load_from_env_file(prefixes: tuple[str, ...]) -> dict[str, str]:
|
||||
merged: dict[str, str] = {}
|
||||
for env_path in (BACKEND_ENV_PATH, ROOT_ENV_LOCAL_PATH):
|
||||
if not env_path.exists():
|
||||
continue
|
||||
try:
|
||||
loaded = dotenv_values(env_path)
|
||||
except OSError as exc:
|
||||
logger.warning('Cannot read %s: %s', env_path, exc)
|
||||
continue
|
||||
for key, value in loaded.items():
|
||||
if key and _matches_prefixes(key, prefixes):
|
||||
merged[key] = value if value is not None else ''
|
||||
return merged
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Public API
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def persist_env_settings(values: dict[str, object]) -> dict[str, str]:
|
||||
"""Persist settings to the canonical store and mirror to ``os.environ``.
|
||||
|
||||
Order:
|
||||
1. Mirror to ``os.environ`` so the current process picks them up
|
||||
immediately.
|
||||
2. Persist to the database (canonical, survives container rebuilds).
|
||||
3. In dev only, best-effort write to ``.env.local`` so local restarts
|
||||
without DB access keep working.
|
||||
"""
|
||||
if not values:
|
||||
return {}
|
||||
|
||||
persisted: dict[str, str] = {}
|
||||
for key, value in values.items():
|
||||
env_value = _to_env_string(value)
|
||||
os.environ[key] = env_value
|
||||
persisted[key] = env_value
|
||||
|
||||
db_ok = _persist_to_db(persisted)
|
||||
file_ok = _persist_to_env_file(persisted)
|
||||
|
||||
if not db_ok and not file_ok:
|
||||
logger.error(
|
||||
'Failed to persist settings %s to BOTH database and .env.local mirror. '
|
||||
'Settings will be lost when the process restarts.',
|
||||
list(persisted.keys()),
|
||||
)
|
||||
|
||||
return persisted
|
||||
|
||||
|
||||
def apply_env_settings(prefixes: tuple[str, ...] = ('WECOM_',)) -> dict[str, object]:
|
||||
"""Load settings from the canonical store and apply to ``os.environ``.
|
||||
|
||||
DB values take priority over env-file values; both are merged so
|
||||
keys that only live in env files (e.g. fresh deploy before any admin
|
||||
edit) are still honored.
|
||||
"""
|
||||
file_values = _load_from_env_file(prefixes)
|
||||
db_values = _load_from_db(prefixes)
|
||||
|
||||
merged: dict[str, str] = {**file_values, **db_values}
|
||||
|
||||
applied: dict[str, object] = {}
|
||||
for key, raw_value in merged.items():
|
||||
parsed = _parse_env_value(key, raw_value)
|
||||
os.environ[key] = _to_env_string(parsed)
|
||||
applied[key] = parsed
|
||||
return applied
|
||||
__all__ = [
|
||||
'BACKEND_ENV_PATH',
|
||||
'LEGACY_BACKEND_ENV_PATH',
|
||||
'ROOT_ENV_LOCAL_PATH',
|
||||
'apply_env_settings',
|
||||
'persist_env_settings',
|
||||
]
|
||||
+5
-92
@@ -1,96 +1,9 @@
|
||||
"""
|
||||
backend/app/errors.py
|
||||
用途:定义后端统一业务异常类型,供全局异常处理器识别并输出标准错误响应。
|
||||
说明:
|
||||
1. AppError 作为基础异常,包含 code/message/http_status/details/retryable。
|
||||
2. 各子类用于表达常见语义(参数错误、未授权、无权限、资源不存在)。
|
||||
3. 业务层可直接 raise 这些异常,避免到处手写 jsonify(error)。
|
||||
|
||||
用途:兼容层 — 权威实现位于 app.core.errors。
|
||||
依赖:app.core.errors。
|
||||
逻辑:存量代码 from app.errors import ... 仍可用;新代码请改用 app.core.errors。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
|
||||
|
||||
@dataclass
|
||||
class AppError(Exception):
|
||||
code: str
|
||||
message: str
|
||||
http_status: int = 400
|
||||
details: dict[str, Any] = field(default_factory=dict)
|
||||
retryable: bool = False
|
||||
|
||||
|
||||
class ValidationError(AppError):
|
||||
def __init__(self, message: str = "Invalid request parameters", *, details: dict[str, Any] | None = None):
|
||||
super().__init__(
|
||||
code="VALIDATION.INVALID_PARAM",
|
||||
message=message,
|
||||
http_status=400,
|
||||
details=details or {},
|
||||
retryable=False,
|
||||
)
|
||||
|
||||
|
||||
class UnauthorizedError(AppError):
|
||||
def __init__(self, message: str = "Unauthorized"):
|
||||
super().__init__(code="AUTH.UNAUTHORIZED", message=message, http_status=401, retryable=False)
|
||||
|
||||
|
||||
class ForbiddenError(AppError):
|
||||
def __init__(self, message: str = "Forbidden"):
|
||||
super().__init__(code="AUTH.FORBIDDEN", message=message, http_status=403, retryable=False)
|
||||
|
||||
|
||||
class NotFoundError(AppError):
|
||||
def __init__(self, message: str = "Resource not found"):
|
||||
super().__init__(code="RESOURCE.NOT_FOUND", message=message, http_status=404, retryable=False)
|
||||
|
||||
|
||||
class ConflictError(AppError):
|
||||
def __init__(
|
||||
self,
|
||||
message: str = "Resource conflict",
|
||||
*,
|
||||
code: str = "RESOURCE.CONFLICT",
|
||||
details: dict[str, Any] | None = None,
|
||||
):
|
||||
super().__init__(
|
||||
code=code,
|
||||
message=message,
|
||||
http_status=409,
|
||||
details=details or {},
|
||||
retryable=False,
|
||||
)
|
||||
|
||||
|
||||
class ServiceUnavailableError(AppError):
|
||||
def __init__(self, message: str = "Service unavailable", *, code: str = "SYSTEM.SERVICE_UNAVAILABLE"):
|
||||
super().__init__(code=code, message=message, http_status=503, retryable=True)
|
||||
|
||||
|
||||
def raise_for_status(message: str, status: int, *, code: str | None = None, details: dict[str, Any] | None = None) -> None:
|
||||
if status == 401:
|
||||
raise UnauthorizedError(message)
|
||||
if status == 403:
|
||||
raise ForbiddenError(message)
|
||||
if status == 404:
|
||||
raise NotFoundError(message)
|
||||
if status == 409:
|
||||
raise ConflictError(message, code=code or "RESOURCE.CONFLICT", details=details)
|
||||
if status == 503:
|
||||
raise ServiceUnavailableError(message, code=code or "SYSTEM.SERVICE_UNAVAILABLE")
|
||||
if status >= 500:
|
||||
raise AppError(
|
||||
code=code or "SYSTEM.INTERNAL_ERROR",
|
||||
message=message,
|
||||
http_status=status,
|
||||
details=details or {},
|
||||
)
|
||||
raise AppError(
|
||||
code=code or "VALIDATION.INVALID_PARAM",
|
||||
message=message,
|
||||
http_status=status,
|
||||
details=details or {},
|
||||
)
|
||||
from app.core.errors import * # noqa: F403
|
||||
@@ -1,10 +1,12 @@
|
||||
"""
|
||||
backend/app/extensions.py
|
||||
|
||||
用途:Flask 扩展实例(db、migrate)集中定义;Wave 1 从 __init__.py 迁入并接线。
|
||||
用途:Flask 扩展单例(SQLAlchemy db、Flask-Migrate migrate)的唯一定义处。
|
||||
依赖:flask_sqlalchemy、flask_migrate。
|
||||
逻辑:create_app 调用 db.init_app(app);models 与各 service 从本模块 import db。
|
||||
逻辑:create_app 调用 db.init_app / migrate.init_app;models 与 services 通过 from app import db 或
|
||||
from app.extensions import db 引用同一实例,避免在 app/__init__.py 与应用工厂混杂定义。
|
||||
"""
|
||||
|
||||
from flask_sqlalchemy import SQLAlchemy
|
||||
from flask_migrate import Migrate
|
||||
|
||||
|
||||
@@ -6,6 +6,12 @@ backend/app/jobs/__init__.py
|
||||
逻辑:Web API enqueue;worker.py 调用 runner.run_forever。
|
||||
"""
|
||||
from app.jobs.types import JobStatus, JobType
|
||||
from app.jobs.queue import enqueue
|
||||
from app.jobs.queue import enqueue, enqueue_clean_job, enqueue_kb_job
|
||||
|
||||
__all__ = ['JobType', 'JobStatus', 'enqueue']
|
||||
__all__ = [
|
||||
'JobType',
|
||||
'JobStatus',
|
||||
'enqueue',
|
||||
'enqueue_kb_job',
|
||||
'enqueue_clean_job',
|
||||
]
|
||||
@@ -1,8 +1,8 @@
|
||||
"""
|
||||
backend/app/jobs/handlers/kb_clean.py
|
||||
|
||||
用途:KB 文档清洗任务 handler。
|
||||
逻辑:Wave 2 包装 knowledge_cleaning.queue_service.process_next_clean_job。
|
||||
用途:KB 文档清洗 / 路径上传任务 handler。
|
||||
逻辑:包装 knowledge_cleaning.tasks.run_clean_job / run_path_upload_job。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -14,11 +14,22 @@ from app.jobs.types import JobType
|
||||
@register_handler(JobType.KB_CLEAN)
|
||||
def run_kb_clean(ctx: JobContext, payload: dict) -> None:
|
||||
"""
|
||||
执行单条 KB 清洗任务。
|
||||
执行单条 KB 清洗或路径上传任务。
|
||||
Args:
|
||||
ctx: Worker 上下文。
|
||||
payload: 含 document_id 等字段。
|
||||
payload: 须含 job_id;raw_job_type 为 path_upload 时走路径上传分支。
|
||||
"""
|
||||
ctx.logger.info('kb_clean handler skeleton invoked payload=%s', payload)
|
||||
# Wave 2: from app.services.knowledge_cleaning.queue_service import process_job
|
||||
raise NotImplementedError('kb_clean handler pending Wave 2')
|
||||
job_id = int(payload['job_id'])
|
||||
raw_type = str(payload.get('raw_job_type') or 'clean').strip()
|
||||
|
||||
from app.services.knowledge_cleaning.tasks import run_clean_job, run_path_upload_job
|
||||
|
||||
if raw_type == 'path_upload':
|
||||
ok, message = run_path_upload_job(job_id)
|
||||
else:
|
||||
ok, message = run_clean_job(job_id)
|
||||
|
||||
level = ctx.logger.info if ok else ctx.logger.warning
|
||||
level('kb_clean job_id=%s raw_type=%s ok=%s message=%s', job_id, raw_type, ok, message)
|
||||
if not ok:
|
||||
raise RuntimeError(message)
|
||||
@@ -2,7 +2,7 @@
|
||||
backend/app/jobs/handlers/kb_dify_sync.py
|
||||
|
||||
用途:KB 文档同步至 Dify 任务 handler。
|
||||
逻辑:Wave 2 包装 knowledge_cleaning.dify_sync_service。
|
||||
逻辑:包装 knowledge_cleaning.tasks.run_sync_job。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -13,6 +13,17 @@ from app.jobs.types import JobType
|
||||
|
||||
@register_handler(JobType.KB_DIFY_SYNC)
|
||||
def run_kb_dify_sync(ctx: JobContext, payload: dict) -> None:
|
||||
"""同步已清洗文档到 Dify。"""
|
||||
ctx.logger.info('kb_dify_sync handler skeleton invoked payload=%s', payload)
|
||||
raise NotImplementedError('kb_dify_sync handler pending Wave 2')
|
||||
"""
|
||||
同步已清洗文档到 Dify。
|
||||
Args:
|
||||
ctx: Worker 上下文。
|
||||
payload: 须含 job_id(KbJob 主键)。
|
||||
"""
|
||||
job_id = int(payload['job_id'])
|
||||
from app.services.knowledge_cleaning.tasks import run_sync_job
|
||||
|
||||
ok, message = run_sync_job(job_id)
|
||||
level = ctx.logger.info if ok else ctx.logger.warning
|
||||
level('kb_dify_sync job_id=%s ok=%s message=%s', job_id, ok, message)
|
||||
if not ok:
|
||||
raise RuntimeError(message)
|
||||
@@ -15,5 +15,12 @@ from app.services.shipping_notice.queue_service import run_shipping_notice_job
|
||||
|
||||
@register_handler(JobType.SHIPPING_NOTICE_RUN)
|
||||
def run_shipping_notice(ctx: JobContext, payload: dict) -> None:
|
||||
"""消费单票发货后台任务。"""
|
||||
run_shipping_notice_job(payload, logger=ctx.logger)
|
||||
"""
|
||||
消费单票发货后台任务。
|
||||
Args:
|
||||
ctx: Worker 上下文。
|
||||
payload: 须含 job_id 或 task_no。
|
||||
"""
|
||||
ok, message = run_shipping_notice_job(payload, logger=ctx.logger)
|
||||
if not ok:
|
||||
raise RuntimeError(message)
|
||||
+309
-13
@@ -1,34 +1,330 @@
|
||||
"""
|
||||
backend/app/jobs/queue.py
|
||||
|
||||
用途:任务入队 API。
|
||||
逻辑:API / services 调用 enqueue;Wave 2 写入 Job 表并 adapter KbJob。
|
||||
用途:通用后台任务入队、领取与完成状态管理,并保留旧 KB 入队兼容入口。
|
||||
依赖:models.Job、jobs.types、Flask app.config、knowledge_cleaning 队列适配层。
|
||||
逻辑:业务服务调用 enqueue 写入 jobs;旧 KB 清洗入口委托 legacy KbJob 队列;worker 调用 claim/finish/fail 完成执行闭环。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import socket
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
from sqlalchemy.exc import OperationalError
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ValidationError
|
||||
from app.jobs.types import JobType
|
||||
from app.models import Job
|
||||
|
||||
ACTIVE_STATUSES = ("queued", "running")
|
||||
TERMINAL_STATUSES = ("success", "failed", "dead", "cancelled")
|
||||
|
||||
|
||||
def _normalize_job_type(job_type: JobType | str) -> str:
|
||||
"""把 JobType 或字符串统一成数据库保存值。"""
|
||||
return str(getattr(job_type, "value", job_type) or "").strip()
|
||||
|
||||
|
||||
def _worker_id() -> str:
|
||||
"""生成当前 worker 标识,用于锁记录和排障。"""
|
||||
try:
|
||||
host = socket.gethostname()
|
||||
except Exception:
|
||||
host = "unknown-host"
|
||||
return f"{host}:{id(db.session)}"
|
||||
|
||||
|
||||
def _find_shipping_notice_job_id(task_no: str) -> int | None:
|
||||
"""
|
||||
按 task_no 查找发货任务对应的 KbJob。
|
||||
Args:
|
||||
task_no: 发货任务号;由 AI 或业务代码传入时可大小写混用。
|
||||
Returns:
|
||||
匹配到的最新 KbJob 主键;未找到返回 None。
|
||||
"""
|
||||
from app import db
|
||||
from app.models import KbJob
|
||||
|
||||
normalized_task_no = str(task_no or '').strip().upper()
|
||||
candidates = (
|
||||
db.session.query(KbJob)
|
||||
.filter(
|
||||
KbJob.job_type == JobType.SHIPPING_NOTICE_RUN.value,
|
||||
KbJob.status.in_(('queued', 'running', 'success', 'failed')),
|
||||
)
|
||||
.order_by(KbJob.id.desc())
|
||||
.limit(50)
|
||||
.all()
|
||||
)
|
||||
for job in candidates:
|
||||
payload_json = job.payload_json or {}
|
||||
if str(payload_json.get('task_no') or '').strip().upper() == normalized_task_no:
|
||||
return job.id
|
||||
return None
|
||||
|
||||
|
||||
def enqueue_kb_job(job_id: int) -> tuple[bool, str]:
|
||||
"""
|
||||
兼容旧知识库后台任务入队入口。
|
||||
|
||||
Args:
|
||||
job_id: KbJob 主键;由清洗、路径上传、Dify 同步等知识库流程传入。
|
||||
Returns:
|
||||
(是否接受入队, 队列状态说明)。
|
||||
"""
|
||||
from app.services.knowledge_cleaning.queue_service import enqueue_kb_job as _enqueue_kb_job
|
||||
|
||||
return _enqueue_kb_job(job_id)
|
||||
|
||||
|
||||
def enqueue_clean_job(job_id: int) -> tuple[bool, str]:
|
||||
"""
|
||||
兼容旧清洗任务入队入口。
|
||||
|
||||
Args:
|
||||
job_id: clean 类型 KbJob 主键。
|
||||
Returns:
|
||||
(是否接受入队, 队列状态说明)。
|
||||
"""
|
||||
return enqueue_kb_job(job_id)
|
||||
|
||||
|
||||
def enqueue(
|
||||
job_type: JobType,
|
||||
job_type: JobType | str,
|
||||
payload: dict[str, Any],
|
||||
*,
|
||||
domain: str = "default",
|
||||
business_ref: str | None = None,
|
||||
created_by_id: int | None = None,
|
||||
priority: int = 0,
|
||||
max_attempts: int = 3,
|
||||
message: str | None = None,
|
||||
dedupe_active: bool = True,
|
||||
correlation_id: str | None = None,
|
||||
scheduled_at: Any = None,
|
||||
) -> int:
|
||||
"""
|
||||
将任务写入队列并返回 job id。
|
||||
核心逻辑:Wave 2 实现 store.create + KbJob adapter。
|
||||
将任务写入通用 jobs 队列并返回 job id。
|
||||
|
||||
Args:
|
||||
job_type: 任务类型。
|
||||
payload: 任务参数 JSON。
|
||||
correlation_id: 关联业务 id(如 kb_document_id)。
|
||||
scheduled_at: 延迟执行时间(可选)。
|
||||
Returns:
|
||||
Job 主键。
|
||||
Raises:
|
||||
NotImplementedError: Wave 0 占位。
|
||||
payload: JSON payload。
|
||||
domain: 业务域,如 shipping_notice。
|
||||
business_ref: 业务幂等锚点,如发货任务号。
|
||||
created_by_id: 创建人。
|
||||
priority: 优先级,数值越大越先执行。
|
||||
max_attempts: 最大尝试次数。
|
||||
message: 初始状态说明。
|
||||
dedupe_active: 是否复用 active 状态的同业务任务。
|
||||
correlation_id: 兼容旧接口;business_ref 为空时作为业务锚点。
|
||||
scheduled_at: 未来时间则延迟到该时间后才可被 worker 领取。
|
||||
"""
|
||||
raise NotImplementedError('jobs.enqueue is not wired until Wave 2')
|
||||
normalized_type = _normalize_job_type(job_type)
|
||||
if normalized_type in {JobType.KB_CLEAN.value, JobType.KB_DIFY_SYNC.value}:
|
||||
raw_job_id = (payload or {}).get("job_id") if isinstance(payload, dict) else None
|
||||
if not raw_job_id:
|
||||
raise ValidationError("job_id is required")
|
||||
ok, message_text = enqueue_kb_job(int(raw_job_id))
|
||||
if not ok:
|
||||
raise ValidationError(message_text or "enqueue kb job failed")
|
||||
return int(raw_job_id)
|
||||
|
||||
normalized_domain = str(domain or "").strip() or "default"
|
||||
normalized_ref = str(business_ref or correlation_id or "").strip() or None
|
||||
if not normalized_type:
|
||||
raise ValueError("job_type is required")
|
||||
if not isinstance(payload, dict):
|
||||
raise ValueError("payload must be a dict")
|
||||
|
||||
if dedupe_active and normalized_ref:
|
||||
existing = (
|
||||
db.session.query(Job)
|
||||
.filter(
|
||||
Job.domain == normalized_domain,
|
||||
Job.job_type == normalized_type,
|
||||
Job.business_ref == normalized_ref,
|
||||
Job.status.in_(ACTIVE_STATUSES),
|
||||
)
|
||||
.order_by(Job.created_at.desc(), Job.id.desc())
|
||||
.first()
|
||||
)
|
||||
if existing:
|
||||
return int(existing.id)
|
||||
|
||||
now = datetime.utcnow()
|
||||
queue_at = scheduled_at if isinstance(scheduled_at, datetime) else now
|
||||
job = Job(
|
||||
domain=normalized_domain,
|
||||
job_type=normalized_type,
|
||||
status="queued",
|
||||
priority=int(priority or 0),
|
||||
business_ref=normalized_ref,
|
||||
payload_json=payload,
|
||||
progress=0,
|
||||
message=message or "等待后台处理",
|
||||
attempts=0,
|
||||
max_attempts=max(1, int(max_attempts or 1)),
|
||||
created_by_id=created_by_id,
|
||||
created_at=queue_at,
|
||||
updated_at=now,
|
||||
)
|
||||
db.session.add(job)
|
||||
db.session.commit()
|
||||
return int(job.id)
|
||||
|
||||
|
||||
def recover_stale_jobs(*, domain: str, timeout_seconds: float, job_type: str | JobType | None = None) -> int:
|
||||
"""回收指定业务域内超时 running 的通用任务。"""
|
||||
cutoff = datetime.utcnow() - timedelta(seconds=float(timeout_seconds))
|
||||
query = (
|
||||
db.session.query(Job)
|
||||
.filter(
|
||||
Job.domain == domain,
|
||||
Job.status == "running",
|
||||
Job.started_at.isnot(None),
|
||||
Job.started_at < cutoff,
|
||||
)
|
||||
)
|
||||
normalized_type = _normalize_job_type(job_type) if job_type else ""
|
||||
if normalized_type:
|
||||
query = query.filter(Job.job_type == normalized_type)
|
||||
stale_jobs = query.order_by(Job.started_at.asc(), Job.id.asc()).all()
|
||||
if not stale_jobs:
|
||||
return 0
|
||||
|
||||
now = datetime.utcnow()
|
||||
for job in stale_jobs:
|
||||
if int(job.attempts or 0) < int(job.max_attempts or 1):
|
||||
job.status = "queued"
|
||||
job.message = "任务执行超时,已回收等待重试"
|
||||
job.locked_by = None
|
||||
job.locked_at = None
|
||||
job.started_at = None
|
||||
job.updated_at = now
|
||||
continue
|
||||
job.status = "failed"
|
||||
job.error_message = f"任务执行超时(超过 {int(timeout_seconds)}s)"
|
||||
job.message = job.error_message
|
||||
job.progress = 100
|
||||
job.locked_by = None
|
||||
job.locked_at = None
|
||||
job.finished_at = now
|
||||
job.updated_at = now
|
||||
db.session.commit()
|
||||
return len(stale_jobs)
|
||||
|
||||
|
||||
def claim_next_job(*, domain: str, job_types: list[str | JobType] | None = None, worker_id: str | None = None) -> Job | None:
|
||||
"""原子领取指定业务域下一条 queued 任务。"""
|
||||
normalized_types = [_normalize_job_type(item) for item in (job_types or []) if _normalize_job_type(item)]
|
||||
now = datetime.utcnow()
|
||||
try:
|
||||
query = db.session.query(Job).filter(
|
||||
Job.domain == domain,
|
||||
Job.status == "queued",
|
||||
Job.created_at <= now,
|
||||
)
|
||||
if normalized_types:
|
||||
query = query.filter(Job.job_type.in_(normalized_types))
|
||||
job = (
|
||||
query.order_by(Job.priority.desc(), Job.created_at.asc(), Job.id.asc())
|
||||
.with_for_update(skip_locked=True)
|
||||
.first()
|
||||
)
|
||||
except OperationalError:
|
||||
db.session.rollback()
|
||||
raise
|
||||
|
||||
if not job:
|
||||
db.session.rollback()
|
||||
return None
|
||||
|
||||
job.status = "running"
|
||||
job.started_at = job.started_at or now
|
||||
job.locked_at = now
|
||||
job.locked_by = worker_id or _worker_id()
|
||||
job.attempts = int(job.attempts or 0) + 1
|
||||
job.progress = max(int(job.progress or 0), 1)
|
||||
job.message = "worker 已领取任务"
|
||||
job.updated_at = now
|
||||
db.session.commit()
|
||||
return job
|
||||
|
||||
|
||||
def finish_job(job: Job, *, result: dict[str, Any] | None = None, message: str | None = None) -> None:
|
||||
"""标记任务成功完成。"""
|
||||
now = datetime.utcnow()
|
||||
job.status = "success"
|
||||
job.progress = 100
|
||||
job.result_json = result or {}
|
||||
job.message = message or "任务处理完成"
|
||||
job.error_message = None
|
||||
job.locked_by = None
|
||||
job.locked_at = None
|
||||
job.finished_at = now
|
||||
job.updated_at = now
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def fail_job(job: Job, *, error: str, result: dict[str, Any] | None = None, retryable: bool = False) -> None:
|
||||
"""标记任务失败;retryable 且未达上限时重新排队。"""
|
||||
now = datetime.utcnow()
|
||||
can_retry = retryable and int(job.attempts or 0) < int(job.max_attempts or 1)
|
||||
job.status = "queued" if can_retry else "failed"
|
||||
job.progress = 0 if can_retry else 100
|
||||
job.result_json = result or {}
|
||||
job.error_message = str(error or "job failed")[:1000]
|
||||
job.message = "任务失败,等待重试" if can_retry else job.error_message
|
||||
job.locked_by = None
|
||||
job.locked_at = None
|
||||
job.finished_at = None if can_retry else now
|
||||
job.updated_at = now
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def process_next_job(
|
||||
*,
|
||||
ctx: Any,
|
||||
domain: str,
|
||||
job_types: list[str | JobType] | None = None,
|
||||
timeout_config_key: str | None = None,
|
||||
default_timeout_seconds: float = 300,
|
||||
) -> tuple[bool, str]:
|
||||
"""领取并分发一条通用任务。"""
|
||||
import app.jobs.handlers # noqa: F401
|
||||
from app.jobs.registry import get_handler
|
||||
|
||||
timeout_seconds = float(
|
||||
current_app.config.get(timeout_config_key, default_timeout_seconds)
|
||||
if timeout_config_key
|
||||
else default_timeout_seconds
|
||||
)
|
||||
recover_stale_jobs(domain=domain, timeout_seconds=timeout_seconds)
|
||||
job = claim_next_job(domain=domain, job_types=job_types)
|
||||
if not job:
|
||||
return False, "no_job"
|
||||
|
||||
job_id = int(job.id)
|
||||
job_type_value = str(job.job_type or "").strip()
|
||||
payload = dict(job.payload_json or {})
|
||||
payload.setdefault("job_id", job_id)
|
||||
handler = get_handler(JobType(job_type_value))
|
||||
if handler is None:
|
||||
fail_job(job, error=f"no handler registered for {job.job_type}")
|
||||
return True, "missing_handler"
|
||||
|
||||
try:
|
||||
handler(ctx, payload)
|
||||
refreshed = db.session.get(Job, job_id)
|
||||
if refreshed and refreshed.status == "running":
|
||||
finish_job(refreshed, message="任务处理完成")
|
||||
return True, job_type_value
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
refreshed = db.session.get(Job, job_id)
|
||||
if refreshed:
|
||||
fail_job(refreshed, error=str(exc), retryable=True)
|
||||
raise
|
||||
+33
-16
@@ -2,37 +2,54 @@
|
||||
backend/app/jobs/runner.py
|
||||
|
||||
用途:Worker 主循环 poll → dispatch → ack/fail。
|
||||
逻辑:worker.py 调用 run_forever(ctx);Wave 2 接入 store 与 registry。
|
||||
逻辑:worker.py 调用 run_forever(ctx);claim 走 store,执行走 registry handler。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from app.jobs.context import JobContext
|
||||
from app.jobs.registry import get_handler
|
||||
from app.jobs import store
|
||||
from app.jobs.registry import get_handler
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from app.jobs.context import JobContext
|
||||
|
||||
|
||||
def run_forever(ctx: JobContext, *, poll_interval_seconds: float = 2.0) -> None:
|
||||
def _resolve_poll_seconds(ctx: JobContext) -> float:
|
||||
"""按队列配置读取轮询间隔。"""
|
||||
queues = ctx.extras.get('queues') or ['kb']
|
||||
if 'shipping' in queues and 'kb' not in queues:
|
||||
return float(ctx.config.get('SHIPPING_NOTICE_WORKER_POLL_SECONDS', 2))
|
||||
return float(ctx.config.get('KB_WORKER_POLL_SECONDS', 2))
|
||||
|
||||
|
||||
def run_forever(ctx: JobContext, *, poll_interval_seconds: float | None = None) -> None:
|
||||
"""
|
||||
持续轮询并执行任务。
|
||||
核心逻辑:claim_next → get_handler → handler(ctx, payload) → 更新状态。
|
||||
核心逻辑:claim_next → get_handler → handler(ctx, payload);异常时 mark_failed。
|
||||
Args:
|
||||
ctx: Worker 上下文。
|
||||
poll_interval_seconds: 无任务时的休眠秒数。
|
||||
ctx: Worker 上下文(extras.queues 指定消费队列)。
|
||||
poll_interval_seconds: 无任务时的休眠秒数;默认按队列读 config。
|
||||
"""
|
||||
ctx.logger.info('Job runner started (skeleton mode — Wave 2 will enable claim loop)')
|
||||
queues = ctx.extras.get('queues') or ['kb']
|
||||
poll = poll_interval_seconds if poll_interval_seconds is not None else _resolve_poll_seconds(ctx)
|
||||
ctx.logger.info('Job runner started queues=%s poll_seconds=%s', queues, poll)
|
||||
|
||||
while True:
|
||||
try:
|
||||
job = store.claim_next()
|
||||
except NotImplementedError:
|
||||
time.sleep(poll_interval_seconds)
|
||||
continue
|
||||
job = store.claim_next(queues=queues)
|
||||
if not job:
|
||||
time.sleep(poll_interval_seconds)
|
||||
time.sleep(poll)
|
||||
continue
|
||||
|
||||
handler = get_handler(job['job_type'])
|
||||
if not handler:
|
||||
ctx.logger.error('No handler for job_type=%s', job.get('job_type'))
|
||||
ctx.logger.error('No handler for job_type=%s job_id=%s', job.get('job_type'), job.get('id'))
|
||||
store.mark_failed(job['id'], message=f'no handler for {job.get("job_type")}')
|
||||
continue
|
||||
handler(ctx, job.get('payload') or {})
|
||||
|
||||
try:
|
||||
handler(ctx, job.get('payload') or {})
|
||||
except Exception as exc:
|
||||
ctx.logger.exception('Handler failed job_id=%s', job.get('id'))
|
||||
store.mark_failed(job['id'], message=str(exc))
|
||||
@@ -1,20 +1,106 @@
|
||||
"""
|
||||
backend/app/jobs/store.py
|
||||
|
||||
用途:Job 表 CRUD(claim、update status)。
|
||||
逻辑:runner 通过 claim_next 获取待执行任务;Wave 2 落地 SQLAlchemy 模型。
|
||||
用途:Job 认领与状态读写(Wave 2:KbJob 双轨 adapter,无新表)。
|
||||
依赖:KbJob、各域 queue_service 的 claim/recover 逻辑。
|
||||
逻辑:runner 通过 claim_next 获取待执行任务;返回归一化 dict 供 handler 分发。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.jobs.types import QUEUE_KB_JOB_TYPES, JobType, handler_type_for_kb_job
|
||||
from app.models import KbJob
|
||||
|
||||
def claim_next() -> dict[str, Any] | None:
|
||||
|
||||
def _normalize_kb_job(job: KbJob) -> dict[str, Any]:
|
||||
"""
|
||||
认领下一条待执行 Job(SELECT FOR UPDATE SKIP LOCKED)。
|
||||
将 KbJob ORM 实例转为 runner/handler 使用的归一化任务 dict。
|
||||
Args:
|
||||
job: 已 claim 的 KbJob。
|
||||
Returns:
|
||||
job 字典或 None。
|
||||
Raises:
|
||||
NotImplementedError: Wave 0 占位。
|
||||
含 id、job_type(handler 键)、payload、raw_job_type 的字典。
|
||||
"""
|
||||
raise NotImplementedError('jobs.store.claim_next is not wired until Wave 2')
|
||||
handler_type = handler_type_for_kb_job(job.job_type)
|
||||
if handler_type is None:
|
||||
raise ValueError(f'unsupported kb job_type={job.job_type!r}')
|
||||
|
||||
return {
|
||||
'id': job.id,
|
||||
'job_type': handler_type,
|
||||
'raw_job_type': job.job_type,
|
||||
'payload': {
|
||||
'job_id': job.id,
|
||||
'raw_job_type': job.job_type,
|
||||
**(job.payload_json or {}),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def claim_next(*, queues: list[str] | None = None) -> dict[str, Any] | None:
|
||||
"""
|
||||
认领下一条待执行 Job(SELECT FOR UPDATE SKIP LOCKED,委托各域 queue_service)。
|
||||
核心逻辑:按 queues 顺序依次尝试 kb / shipping 队列;先 recover 卡死 running 任务。
|
||||
Args:
|
||||
queues: worker 消费的队列名,如 ['kb'] 或 ['kb', 'shipping']。
|
||||
Returns:
|
||||
归一化 job dict 或 None(无任务)。
|
||||
"""
|
||||
queue_names = [q.strip() for q in (queues or ['kb']) if q and q.strip()]
|
||||
if not queue_names:
|
||||
queue_names = ['kb']
|
||||
|
||||
# [STEP 1] 超时回收(按队列涉及的类型)
|
||||
allowed_types: set[str] = set()
|
||||
for name in queue_names:
|
||||
allowed_types.update(QUEUE_KB_JOB_TYPES.get(name, frozenset()))
|
||||
|
||||
if allowed_types & QUEUE_KB_JOB_TYPES['kb']:
|
||||
from app.services.knowledge_cleaning.queue_service import recover_stale_running_jobs
|
||||
|
||||
recover_stale_running_jobs()
|
||||
if 'shipping_notice_run' in allowed_types:
|
||||
from app.services.shipping_notice.queue_service import recover_stale_shipping_notice_jobs
|
||||
|
||||
recover_stale_shipping_notice_jobs()
|
||||
|
||||
# [STEP 2] 按队列优先级 claim
|
||||
for name in queue_names:
|
||||
if name == 'kb':
|
||||
from app.services.knowledge_cleaning.queue_service import claim_next_kb_job
|
||||
|
||||
job = claim_next_kb_job()
|
||||
if job:
|
||||
return _normalize_kb_job(job)
|
||||
elif name == 'shipping':
|
||||
from app.services.shipping_notice.queue_service import claim_next_shipping_notice_job
|
||||
|
||||
job = claim_next_shipping_notice_job()
|
||||
if job:
|
||||
return _normalize_kb_job(job)
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def mark_failed(job_id: int, *, message: str) -> None:
|
||||
"""
|
||||
handler 未捕获异常时,将 KbJob 标记为 failed。
|
||||
Args:
|
||||
job_id: KbJob 主键。
|
||||
message: 失败原因(截断至 1000 字符)。
|
||||
"""
|
||||
from datetime import datetime
|
||||
|
||||
from app import db
|
||||
|
||||
job = db.session.get(KbJob, job_id)
|
||||
if not job or job.status != 'running':
|
||||
return
|
||||
|
||||
now = datetime.utcnow()
|
||||
job.status = 'failed'
|
||||
job.error_message = message[:1000]
|
||||
job.message = message[:500]
|
||||
job.finished_at = now
|
||||
job.progress = 100
|
||||
db.session.commit()
|
||||
@@ -1,8 +1,8 @@
|
||||
"""
|
||||
backend/app/jobs/types.py
|
||||
|
||||
用途:Job 类型与状态枚举。
|
||||
逻辑:handlers 与 queue 通过 JobType 注册;store 持久化 status 字符串。
|
||||
用途:Job 类型与状态枚举;KbJob.job_type 与 handler JobType 的双向映射。
|
||||
逻辑:handlers 与 queue 通过 JobType 注册;store 持久化仍走 KbJob 表(Wave 2 双轨)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -10,7 +10,7 @@ from enum import StrEnum
|
||||
|
||||
|
||||
class JobType(StrEnum):
|
||||
"""后台任务类型。"""
|
||||
"""后台任务类型(handler 注册键)。"""
|
||||
|
||||
KB_CLEAN = 'kb_clean'
|
||||
KB_DIFY_SYNC = 'kb_dify_sync'
|
||||
@@ -21,10 +21,54 @@ class JobType(StrEnum):
|
||||
|
||||
|
||||
class JobStatus(StrEnum):
|
||||
"""Job 生命周期状态。"""
|
||||
"""通用 Job 生命周期状态(Wave 4 通用 Job 表预留;当前 KbJob 仍用 queued/running/success/failed)。"""
|
||||
|
||||
PENDING = 'pending'
|
||||
RUNNING = 'running'
|
||||
SUCCEEDED = 'succeeded'
|
||||
FAILED = 'failed'
|
||||
DEAD = 'dead'
|
||||
|
||||
|
||||
# KbJob.job_type 字符串 → handler JobType
|
||||
_KB_JOB_TYPE_TO_HANDLER: dict[str, JobType] = {
|
||||
'clean': JobType.KB_CLEAN,
|
||||
'path_upload': JobType.KB_CLEAN,
|
||||
'sync_dify': JobType.KB_DIFY_SYNC,
|
||||
'shipping_notice_run': JobType.SHIPPING_NOTICE_RUN,
|
||||
}
|
||||
|
||||
# handler JobType → 写入 KbJob 时使用的 job_type
|
||||
_HANDLER_TO_KB_JOB_TYPE: dict[JobType, str] = {
|
||||
JobType.KB_CLEAN: 'clean',
|
||||
JobType.KB_DIFY_SYNC: 'sync_dify',
|
||||
JobType.SHIPPING_NOTICE_RUN: 'shipping_notice_run',
|
||||
}
|
||||
|
||||
# worker --queues 参数 → 可消费的 KbJob.job_type 集合
|
||||
QUEUE_KB_JOB_TYPES: dict[str, frozenset[str]] = {
|
||||
'kb': frozenset({'clean', 'path_upload', 'sync_dify'}),
|
||||
'shipping': frozenset({'shipping_notice_run'}),
|
||||
}
|
||||
|
||||
|
||||
def handler_type_for_kb_job(kb_job_type: str) -> JobType | None:
|
||||
"""
|
||||
将 KbJob.job_type 映射为 handler 注册用的 JobType。
|
||||
Args:
|
||||
kb_job_type: KbJob 表 job_type 列值。
|
||||
Returns:
|
||||
对应 JobType;未知类型返回 None。
|
||||
"""
|
||||
return _KB_JOB_TYPE_TO_HANDLER.get(str(kb_job_type or '').strip())
|
||||
|
||||
|
||||
def kb_job_type_for_handler(job_type: JobType) -> str | None:
|
||||
"""
|
||||
将 handler JobType 映射为写入 KbJob 的 job_type 字符串。
|
||||
Args:
|
||||
job_type: handler 注册键。
|
||||
Returns:
|
||||
KbJob.job_type 值;path_upload 等需调用方显式指定时不经此函数。
|
||||
"""
|
||||
return _HANDLER_TO_KB_JOB_TYPE.get(job_type)
|
||||
@@ -1,900 +0,0 @@
|
||||
from datetime import datetime
|
||||
from typing import Optional, List
|
||||
from sqlalchemy import String, Text, Integer, ForeignKey, JSON, DateTime, Index, Boolean, UniqueConstraint, LargeBinary, Float, text
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
from app import db
|
||||
from werkzeug.security import generate_password_hash, check_password_hash
|
||||
|
||||
class Base(db.Model):
|
||||
"""
|
||||
基础模型类,设置为抽象基类
|
||||
"""
|
||||
__abstract__ = True
|
||||
|
||||
# RBAC 关联表:用户与 Agent 的多对多关系
|
||||
# 用于存储用户拥有哪些 Agent 的访问权限
|
||||
user_agent_permissions = db.Table(
|
||||
'user_agent_permissions',
|
||||
db.Column('user_id', ForeignKey('users.id'), primary_key=True),
|
||||
db.Column('agent_id', ForeignKey('agents.id'), primary_key=True)
|
||||
)
|
||||
|
||||
class ZlLanguage(Base):
|
||||
"""
|
||||
多语言配置表
|
||||
用途:存储系统支持的语言列表
|
||||
"""
|
||||
__tablename__ = 'zl_languages'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
code: Mapped[str] = mapped_column(String(10), unique=True) # en, zh-CN, zh-TW, th
|
||||
name: Mapped[str] = mapped_column(String(50)) # English, 简体中文, ...
|
||||
is_active: Mapped[bool] = mapped_column(default=True)
|
||||
|
||||
class Department(Base):
|
||||
"""
|
||||
部门表
|
||||
用途:存储公司部门列表
|
||||
"""
|
||||
__tablename__ = 'departments'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
name: Mapped[str] = mapped_column(String(100), unique=True)
|
||||
code: Mapped[Optional[str]] = mapped_column(String(50), unique=True) # 部门编号
|
||||
company: Mapped[Optional[str]] = mapped_column(String(100)) # 所属公司
|
||||
description: Mapped[Optional[str]] = mapped_column(Text)
|
||||
|
||||
class UserHomepageConfig(Base):
|
||||
"""
|
||||
用户首页配置表
|
||||
用途:存储用户自定义的首页布局与配置
|
||||
"""
|
||||
__tablename__ = 'user_homepage_configs'
|
||||
|
||||
user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), primary_key=True)
|
||||
layout: Mapped[dict] = mapped_column(JSON, default={}) # 存储模块布局配置
|
||||
# 示例: { "modules": [{"id": "favorites", "x": 0, "y": 0}, {"id": "agents", "x": 0, "y": 1}] }
|
||||
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
class UserFavoriteAgent(Base):
|
||||
"""
|
||||
用户收藏 Agent 表
|
||||
用途:存储用户收藏的 Agent
|
||||
"""
|
||||
__tablename__ = 'user_favorite_agents'
|
||||
|
||||
user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), primary_key=True)
|
||||
agent_id: Mapped[int] = mapped_column(ForeignKey('agents.id'), primary_key=True)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
|
||||
class UserDefaultAgent(Base):
|
||||
"""
|
||||
用户默认 Agent 表 (嵌入首页)
|
||||
用途:存储用户设置的默认嵌入 Agent (最多2个)
|
||||
"""
|
||||
__tablename__ = 'user_default_agents'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
user_id: Mapped[int] = mapped_column(ForeignKey('users.id'))
|
||||
agent_id: Mapped[int] = mapped_column(ForeignKey('agents.id'))
|
||||
sort_order: Mapped[int] = mapped_column(default=0) # 排序,0为第一个,1为第二个
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
|
||||
class User(Base):
|
||||
"""
|
||||
用户表
|
||||
用途:存储系统用户信息
|
||||
核心逻辑:包含部门、角色等字段,关联 Agent 权限
|
||||
"""
|
||||
__tablename__ = 'users'
|
||||
|
||||
# 主键 ID
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
# 用户名,唯一且带索引
|
||||
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))
|
||||
# 角色:admin 或 user
|
||||
role: Mapped[str] = mapped_column(String(20), default='user')
|
||||
# 账号状态:active (正常), pending (待审批), disabled (禁用)
|
||||
status: Mapped[str] = mapped_column(String(20), default='active')
|
||||
# 密码哈希
|
||||
password_hash: Mapped[Optional[str]] = mapped_column(String(255))
|
||||
# 首选语言
|
||||
language: Mapped[str] = mapped_column(String(10), default='zh-CN')
|
||||
# 主题偏好: light / dark / system
|
||||
theme_preference: Mapped[str] = mapped_column(String(10), default='system')
|
||||
# 企业微信关联字段
|
||||
wecom_userid: Mapped[Optional[str]] = mapped_column(String(128), unique=True, nullable=True)
|
||||
wecom_unionid: Mapped[Optional[str]] = mapped_column(String(128), unique=True, nullable=True)
|
||||
|
||||
# 真实姓名
|
||||
real_name: Mapped[Optional[str]] = mapped_column(String(50))
|
||||
# 公司工号,唯一
|
||||
employee_id: Mapped[Optional[str]] = mapped_column(String(50), unique=True)
|
||||
# 手机号,唯一
|
||||
phone_number: Mapped[Optional[str]] = mapped_column(String(20), unique=True)
|
||||
|
||||
# 默认嵌入的 Agent ID (忽略权限检查)
|
||||
default_agent_id: Mapped[Optional[int]] = mapped_column(ForeignKey('agents.id'))
|
||||
|
||||
# 关系:用户拥有的 Agent 权限 (多对多)
|
||||
agents: Mapped[List["Agent"]] = relationship(
|
||||
secondary=user_agent_permissions,
|
||||
back_populates="users"
|
||||
)
|
||||
|
||||
# 密码重置 Token
|
||||
reset_token: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
|
||||
reset_token_expiry: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
|
||||
def set_password(self, password):
|
||||
self.password_hash = generate_password_hash(password)
|
||||
|
||||
def check_password(self, password):
|
||||
if not self.password_hash:
|
||||
return False
|
||||
return check_password_hash(self.password_hash, password)
|
||||
|
||||
class Agent(Base):
|
||||
"""
|
||||
AI 应用配置表
|
||||
用途:存储接入的 Dify Agent 配置信息
|
||||
核心逻辑:存储 Dify App ID 和 API Key,控制应用开关
|
||||
"""
|
||||
__tablename__ = 'agents'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
# 应用名称
|
||||
name: Mapped[str] = mapped_column(String(100))
|
||||
# 应用描述
|
||||
description: Mapped[Optional[str]] = mapped_column(Text)
|
||||
# 图标 URL
|
||||
icon_url: Mapped[Optional[str]] = mapped_column(String(255))
|
||||
|
||||
# Dify 配置:App ID (唯一,对于 iframe 模式可选)
|
||||
dify_app_id: Mapped[Optional[str]] = mapped_column(String(100), unique=True, nullable=True)
|
||||
# Dify 配置:API Key (实际生产应加密存储,对于 iframe 模式可选)
|
||||
dify_api_key: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
|
||||
|
||||
# 类型:api (默认) 或 iframe
|
||||
type: Mapped[str] = mapped_column(String(20), default='api')
|
||||
# 自定义 API Base URL (覆盖全局配置)
|
||||
api_base_url: Mapped[Optional[str]] = mapped_column(String(255))
|
||||
# 额外配置 (JSON),用于存储 iframe_url 等
|
||||
extra_config: Mapped[Optional[dict]] = mapped_column(JSON)
|
||||
|
||||
# 是否激活
|
||||
is_active: Mapped[bool] = mapped_column(default=True)
|
||||
# 创建时间
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
|
||||
# 关系:拥有该应用权限的用户 (多对多)
|
||||
users: Mapped[List["User"]] = relationship(
|
||||
secondary=user_agent_permissions,
|
||||
back_populates="agents"
|
||||
)
|
||||
|
||||
class ChatSession(Base):
|
||||
"""
|
||||
聊天会话表
|
||||
用途:独立持久化会话元数据,使生成中会话也能立即出现在历史记录中
|
||||
"""
|
||||
__tablename__ = 'chat_sessions'
|
||||
__table_args__ = (
|
||||
Index('ix_chat_sessions_user_agent_last_active', 'user_id', 'agent_id', 'last_active_at'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
session_id: Mapped[str] = mapped_column(String(100), unique=True, index=True)
|
||||
user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), index=True)
|
||||
agent_id: Mapped[int] = mapped_column(ForeignKey('agents.id'), index=True)
|
||||
title: Mapped[str] = mapped_column(String(255), default='')
|
||||
status: Mapped[str] = mapped_column(String(20), default='running')
|
||||
external_conversation_id: Mapped[Optional[str]] = mapped_column(String(100), index=True, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
last_active_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
|
||||
class ChatLog(Base):
|
||||
"""
|
||||
对话日志表
|
||||
用途:存储用户与 Agent 的对话记录
|
||||
"""
|
||||
__tablename__ = 'chat_logs'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
user_id: Mapped[int] = mapped_column(ForeignKey('users.id'))
|
||||
agent_id: Mapped[int] = mapped_column(ForeignKey('agents.id'))
|
||||
query: Mapped[str] = mapped_column(Text)
|
||||
answer: Mapped[str] = mapped_column(Text)
|
||||
latency: Mapped[int] = mapped_column(default=0)
|
||||
conversation_id: Mapped[Optional[str]] = mapped_column(String(100))
|
||||
session_id: Mapped[Optional[str]] = mapped_column(String(100), index=True, nullable=True)
|
||||
run_id: Mapped[Optional[int]] = mapped_column(ForeignKey('schedule_runs.id'), index=True, nullable=True)
|
||||
message_type: Mapped[Optional[str]] = mapped_column(String(50), nullable=True)
|
||||
payload: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
|
||||
tokens_used: Mapped[int] = mapped_column(default=0)
|
||||
# Persist citation/source metadata so history messages can still show sources.
|
||||
retriever_resources: Mapped[Optional[list]] = mapped_column(JSON)
|
||||
attribution_parts: Mapped[Optional[list]] = mapped_column(JSON)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
|
||||
# 关联 Feedback
|
||||
feedback: Mapped[Optional["Feedback"]] = relationship(back_populates="chat_log", uselist=False)
|
||||
|
||||
class Feedback(Base):
|
||||
"""
|
||||
反馈表
|
||||
用途:存储用户对回答的评分与评价
|
||||
"""
|
||||
__tablename__ = 'feedbacks'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
chat_log_id: Mapped[int] = mapped_column(ForeignKey('chat_logs.id'), unique=True)
|
||||
score: Mapped[int] = mapped_column(Integer) # 1-5
|
||||
comment: Mapped[Optional[str]] = mapped_column(Text)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
|
||||
chat_log: Mapped["ChatLog"] = relationship(back_populates="feedback")
|
||||
|
||||
class GeneralFeedback(Base):
|
||||
"""
|
||||
通用意见反馈表
|
||||
用于存储 Workspace/Chat 页面提交的通用意见反馈
|
||||
"""
|
||||
__tablename__ = 'general_feedbacks'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), index=True)
|
||||
chat_log_id: Mapped[Optional[int]] = mapped_column(ForeignKey('chat_logs.id'), nullable=True, index=True)
|
||||
username: Mapped[str] = mapped_column(String(50), nullable=False)
|
||||
feedback_type: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
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))
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
|
||||
class PermissionRequest(Base):
|
||||
"""
|
||||
权限申请表
|
||||
用途:存储用户的权限申请记录
|
||||
"""
|
||||
__tablename__ = 'permission_requests'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
user_id: Mapped[int] = mapped_column(ForeignKey('users.id'))
|
||||
agent_id: Mapped[int] = mapped_column(ForeignKey('agents.id'))
|
||||
reason: Mapped[str] = mapped_column(Text)
|
||||
status: Mapped[str] = mapped_column(String(20), default='pending') # pending, approved, rejected
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
reviewed_at: Mapped[Optional[datetime]] = mapped_column(DateTime)
|
||||
|
||||
class QuickQuestion(Base):
|
||||
"""
|
||||
常用问题表
|
||||
用途:存储全局/用户常用问题;全局条目(user_id 为空)可配置标准答案并启用 FAQ 缓存命中。
|
||||
"""
|
||||
__tablename__ = 'quick_questions'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
agent_id: Mapped[int] = mapped_column(ForeignKey('agents.id'))
|
||||
title: Mapped[str] = mapped_column(String(100))
|
||||
question: Mapped[str] = mapped_column(Text)
|
||||
answer: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
aliases: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
||||
cache_enabled: Mapped[bool] = mapped_column(default=False)
|
||||
is_enabled: Mapped[bool] = mapped_column(default=True)
|
||||
hit_count: Mapped[int] = mapped_column(default=0)
|
||||
retriever_resources: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
||||
source_kb_document_ids: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
||||
expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
stale_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
stale_reason: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
stale_kb_document_id: Mapped[Optional[int]] = mapped_column(ForeignKey('kb_documents.id'), nullable=True)
|
||||
sort_order: Mapped[int] = mapped_column(default=0)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
|
||||
class FaqHotCandidate(Base):
|
||||
"""
|
||||
热点 FAQ 候选表
|
||||
用途:离线聚合 ChatLog 后的待审核热点问句与推荐答案(PostgreSQL 存储,不含在线命中)。
|
||||
"""
|
||||
__tablename__ = 'faq_hot_candidates'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('agent_id', 'q_norm', name='uq_faq_hot_candidates_agent_qnorm'),
|
||||
Index('ix_faq_hot_candidates_status_expires', 'status', 'expires_at'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
agent_id: Mapped[int] = mapped_column(ForeignKey('agents.id'), index=True)
|
||||
q_norm: Mapped[str] = mapped_column(String(255))
|
||||
canonical_query: Mapped[str] = mapped_column(Text)
|
||||
answer: Mapped[str] = mapped_column(Text)
|
||||
source_chat_log_id: Mapped[Optional[int]] = mapped_column(ForeignKey('chat_logs.id'), nullable=True)
|
||||
ask_count_7d: Mapped[int] = mapped_column(default=0)
|
||||
user_count_7d: Mapped[int] = mapped_column(default=0)
|
||||
avg_tokens: Mapped[int] = mapped_column(default=0)
|
||||
avg_latency_ms: Mapped[int] = mapped_column(default=0)
|
||||
answer_dominance: Mapped[float] = mapped_column(default=0.0)
|
||||
sample_queries: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
||||
retriever_resources: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
||||
last_asked_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
status: Mapped[str] = mapped_column(String(20), default='candidate') # candidate | promoted | dismissed
|
||||
promoted_quick_question_id: Mapped[Optional[int]] = mapped_column(ForeignKey('quick_questions.id'), nullable=True)
|
||||
deny_until: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
|
||||
class Announcement(Base):
|
||||
"""
|
||||
公告表
|
||||
用途:存储系统公告
|
||||
"""
|
||||
__tablename__ = 'announcements'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
title: Mapped[str] = mapped_column(String(200))
|
||||
content: Mapped[str] = mapped_column(Text)
|
||||
is_active: Mapped[bool] = mapped_column(default=True)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
class LoginAudit(Base):
|
||||
"""
|
||||
登录审计表
|
||||
用途:记录密码登录与企业微信登录结果,便于排障与审计
|
||||
"""
|
||||
__tablename__ = 'login_audits'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
username: Mapped[Optional[str]] = mapped_column(String(50), nullable=True)
|
||||
source: Mapped[str] = mapped_column(String(20), default='password') # password / wecom
|
||||
status: Mapped[str] = mapped_column(String(20), default='success') # success / failed
|
||||
reason: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
match_rules: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
match_operator: Mapped[Optional[str]] = mapped_column(String(8), nullable=True)
|
||||
match_result: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
wecom_userid: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
ip: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
user_agent: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
|
||||
|
||||
class WecomNotifyAudit(Base):
|
||||
"""
|
||||
企业微信触达审计表
|
||||
用途:记录企微消息发送结果与回流点击数据
|
||||
"""
|
||||
__tablename__ = 'wecom_notify_audits'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
event_type: Mapped[str] = mapped_column(String(64), index=True)
|
||||
status: Mapped[str] = mapped_column(String(20), default='sent', index=True) # sent / failed
|
||||
trace_id: Mapped[str] = mapped_column(String(64), unique=True, index=True)
|
||||
user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True, index=True)
|
||||
username: Mapped[Optional[str]] = mapped_column(String(50), nullable=True)
|
||||
wecom_userid: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
title: Mapped[Optional[str]] = mapped_column(String(120), nullable=True)
|
||||
content: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
jump_url: Mapped[Optional[str]] = mapped_column(String(512), nullable=True)
|
||||
error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
error_message: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
opened_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True, index=True)
|
||||
|
||||
|
||||
class AppSetting(Base):
|
||||
"""
|
||||
应用运行时配置表(Key/Value)
|
||||
用途:将企业微信等管理员可编辑的配置长效保存到数据库,
|
||||
避免容器/部署重建后写入 backend/.env 的修改丢失。
|
||||
"""
|
||||
__tablename__ = 'app_settings'
|
||||
|
||||
key: Mapped[str] = mapped_column(String(128), primary_key=True)
|
||||
value: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow
|
||||
)
|
||||
|
||||
|
||||
class KbGroup(Base):
|
||||
"""
|
||||
知识库分组
|
||||
用途:承载数据清洗/知识库管理模块中的分组/知识库
|
||||
"""
|
||||
__tablename__ = 'kb_groups'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('department_id', 'name', name='uq_kb_groups_department_name'),
|
||||
Index('ix_kb_groups_department_active', 'department_id', 'is_active'),
|
||||
Index('ix_kb_groups_dify_dataset_id', 'dify_dataset_id'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
name: Mapped[str] = mapped_column(String(128), index=True)
|
||||
description: Mapped[Optional[str]] = mapped_column(Text)
|
||||
department_id: Mapped[Optional[int]] = mapped_column(Integer, nullable=True, index=True)
|
||||
is_active: Mapped[bool] = mapped_column(Boolean, default=True)
|
||||
dify_dataset_id: Mapped[Optional[str]] = mapped_column(String(128))
|
||||
dify_dataset_name: Mapped[Optional[str]] = mapped_column(String(255))
|
||||
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'))
|
||||
updated_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'))
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
created_by: Mapped[Optional["User"]] = relationship("User", foreign_keys=[created_by_id])
|
||||
updated_by: Mapped[Optional["User"]] = relationship("User", foreign_keys=[updated_by_id])
|
||||
documents: Mapped[List["KbDocument"]] = relationship(
|
||||
"KbDocument",
|
||||
back_populates="group",
|
||||
cascade="all, delete-orphan",
|
||||
)
|
||||
|
||||
|
||||
class KbDocument(Base):
|
||||
"""
|
||||
知识库逻辑文档
|
||||
用途:表示一个文档条目,不直接等同于某一次上传文件
|
||||
"""
|
||||
__tablename__ = 'kb_documents'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('group_id', 'title', name='uq_kb_documents_group_title'),
|
||||
Index('ix_kb_documents_group_status', 'group_id', 'status'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
group_id: Mapped[int] = mapped_column(ForeignKey('kb_groups.id'), index=True)
|
||||
title: Mapped[str] = mapped_column(String(255))
|
||||
description: Mapped[Optional[str]] = mapped_column(Text)
|
||||
status: Mapped[str] = mapped_column(String(32), default='draft', index=True)
|
||||
source_type: Mapped[Optional[str]] = mapped_column(String(32))
|
||||
is_deleted: Mapped[bool] = mapped_column(Boolean, default=False, index=True)
|
||||
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'))
|
||||
updated_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'))
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
group: Mapped["KbGroup"] = relationship("KbGroup", back_populates="documents")
|
||||
created_by: Mapped[Optional["User"]] = relationship("User", foreign_keys=[created_by_id])
|
||||
updated_by: Mapped[Optional["User"]] = relationship("User", foreign_keys=[updated_by_id])
|
||||
versions: Mapped[List["KbDocumentVersion"]] = relationship(
|
||||
"KbDocumentVersion",
|
||||
back_populates="document",
|
||||
cascade="all, delete-orphan",
|
||||
order_by="desc(KbDocumentVersion.version_no)",
|
||||
)
|
||||
|
||||
|
||||
class KbDocumentVersion(Base):
|
||||
"""
|
||||
知识库文档版本
|
||||
用途:记录每次上传、清洗、同步产生的版本信息
|
||||
"""
|
||||
__tablename__ = 'kb_document_versions'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('document_id', 'version_no', name='uq_kb_document_versions_doc_version'),
|
||||
Index('ix_kb_document_versions_doc_status', 'document_id', 'status'),
|
||||
Index('ix_kb_document_versions_sha256', 'sha256'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
document_id: Mapped[int] = mapped_column(ForeignKey('kb_documents.id'), index=True)
|
||||
version_no: Mapped[int] = mapped_column(Integer)
|
||||
status: Mapped[str] = mapped_column(String(32), default='uploaded', index=True)
|
||||
is_current: Mapped[bool] = mapped_column(Boolean, default=True, index=True)
|
||||
source_file_name: Mapped[str] = mapped_column(String(255))
|
||||
source_file_path: Mapped[str] = mapped_column(Text)
|
||||
source_file_ext: Mapped[Optional[str]] = mapped_column(String(32))
|
||||
source_file_size: Mapped[Optional[int]] = mapped_column(Integer)
|
||||
cleaned_file_path: Mapped[Optional[str]] = mapped_column(Text)
|
||||
cleaned_preview_path: Mapped[Optional[str]] = mapped_column(Text)
|
||||
sha256: Mapped[Optional[str]] = mapped_column(String(64))
|
||||
word_count: Mapped[int] = mapped_column(Integer, default=0)
|
||||
error_message: Mapped[Optional[str]] = mapped_column(Text)
|
||||
warnings_json: Mapped[Optional[dict]] = mapped_column(JSON)
|
||||
uploaded_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'))
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
converted_at: Mapped[Optional[datetime]] = mapped_column(DateTime)
|
||||
|
||||
document: Mapped["KbDocument"] = relationship("KbDocument", back_populates="versions")
|
||||
uploaded_by: Mapped[Optional["User"]] = relationship("User", foreign_keys=[uploaded_by_id])
|
||||
jobs: Mapped[List["KbJob"]] = relationship(
|
||||
"KbJob",
|
||||
back_populates="document_version",
|
||||
cascade="all, delete-orphan",
|
||||
)
|
||||
sync_records: Mapped[List["KbDifySyncRecord"]] = relationship(
|
||||
"KbDifySyncRecord",
|
||||
back_populates="document_version",
|
||||
cascade="all, delete-orphan",
|
||||
order_by="desc(KbDifySyncRecord.updated_at)",
|
||||
)
|
||||
|
||||
|
||||
class KbJob(Base):
|
||||
"""
|
||||
知识库后台任务
|
||||
用途:记录上传、清洗、同步等后台任务执行情况
|
||||
"""
|
||||
__tablename__ = 'kb_jobs'
|
||||
__table_args__ = (
|
||||
Index('ix_kb_jobs_status_created', 'status', 'created_at'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
job_type: Mapped[str] = mapped_column(String(32), index=True)
|
||||
status: Mapped[str] = mapped_column(String(32), default='queued', index=True)
|
||||
queue_job_id: Mapped[Optional[str]] = mapped_column(String(64))
|
||||
group_id: Mapped[Optional[int]] = mapped_column(ForeignKey('kb_groups.id'))
|
||||
document_id: Mapped[Optional[int]] = mapped_column(ForeignKey('kb_documents.id'))
|
||||
document_version_id: Mapped[Optional[int]] = mapped_column(ForeignKey('kb_document_versions.id'), index=True)
|
||||
progress: Mapped[int] = mapped_column(Integer, default=0)
|
||||
message: Mapped[Optional[str]] = mapped_column(Text)
|
||||
error_message: Mapped[Optional[str]] = mapped_column(Text)
|
||||
payload_json: Mapped[Optional[dict]] = mapped_column(JSON)
|
||||
result_json: Mapped[Optional[dict]] = mapped_column(JSON)
|
||||
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'))
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
started_at: Mapped[Optional[datetime]] = mapped_column(DateTime)
|
||||
finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime)
|
||||
|
||||
created_by: Mapped[Optional["User"]] = relationship("User", foreign_keys=[created_by_id])
|
||||
document_version: Mapped[Optional["KbDocumentVersion"]] = relationship(
|
||||
"KbDocumentVersion",
|
||||
back_populates="jobs",
|
||||
)
|
||||
|
||||
|
||||
class KbDifySyncRecord(Base):
|
||||
"""
|
||||
知识库 Dify 同步记录
|
||||
用途:记录本地文档版本与 Dify 远端文档之间的同步映射
|
||||
"""
|
||||
__tablename__ = 'kb_dify_sync_records'
|
||||
__table_args__ = (
|
||||
UniqueConstraint(
|
||||
'document_version_id',
|
||||
'remote_document_id',
|
||||
name='uq_kb_dify_sync_records_version_remote'
|
||||
),
|
||||
Index('ix_kb_dify_sync_records_dataset_id', 'dataset_id'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
group_id: Mapped[Optional[int]] = mapped_column(ForeignKey('kb_groups.id'))
|
||||
document_id: Mapped[Optional[int]] = mapped_column(ForeignKey('kb_documents.id'))
|
||||
document_version_id: Mapped[int] = mapped_column(ForeignKey('kb_document_versions.id'), index=True)
|
||||
dataset_id: Mapped[str] = mapped_column(String(128))
|
||||
dataset_name: Mapped[Optional[str]] = mapped_column(String(255))
|
||||
remote_document_id: Mapped[str] = mapped_column(String(128))
|
||||
remote_document_name: Mapped[Optional[str]] = mapped_column(String(255))
|
||||
status: Mapped[str] = mapped_column(String(32), default='pending', index=True)
|
||||
sync_hash: Mapped[Optional[str]] = mapped_column(String(64))
|
||||
error_message: Mapped[Optional[str]] = mapped_column(Text)
|
||||
synced_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'))
|
||||
synced_at: Mapped[Optional[datetime]] = mapped_column(DateTime)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
document_version: Mapped["KbDocumentVersion"] = relationship(
|
||||
"KbDocumentVersion",
|
||||
back_populates="sync_records",
|
||||
)
|
||||
synced_by: Mapped[Optional["User"]] = relationship("User", foreign_keys=[synced_by_id])
|
||||
|
||||
|
||||
class WecomCallbackAudit(Base):
|
||||
"""
|
||||
企业微信回调审计表
|
||||
用途:记录消息与事件回调(安全模式解密后的内容摘要)
|
||||
"""
|
||||
__tablename__ = 'wecom_callback_audits'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
msg_signature: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
timestamp: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
nonce: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
encrypt_raw: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
decrypted_xml: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
msg_type: Mapped[Optional[str]] = mapped_column(String(32), nullable=True, index=True)
|
||||
event: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
|
||||
from_user: Mapped[Optional[str]] = mapped_column(String(128), nullable=True, index=True)
|
||||
agent_id: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
msg_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
|
||||
error_message: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
|
||||
|
||||
class ScheduleTask(Base):
|
||||
__tablename__ = 'schedule_tasks'
|
||||
__table_args__ = (
|
||||
Index('ix_schedule_tasks_enabled_next_run', 'enabled', 'next_run_at'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
schedule_no: Mapped[str] = mapped_column(String(64), unique=True, index=True)
|
||||
name: Mapped[str] = mapped_column(String(128), index=True)
|
||||
schedule_type: Mapped[str] = mapped_column(String(32), default='platform_app')
|
||||
owner_user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), index=True)
|
||||
cron_expr: Mapped[str] = mapped_column(String(64))
|
||||
schedule_timezone: Mapped[str] = mapped_column(String(64), default='Asia/Shanghai', server_default=text("'Asia/Shanghai'"))
|
||||
wait_seconds: Mapped[int] = mapped_column(Integer, default=0)
|
||||
dify_agent_id: Mapped[Optional[int]] = mapped_column(ForeignKey('agents.id'), nullable=True, index=True)
|
||||
platform_api_path: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)
|
||||
data_source_type: Mapped[str] = mapped_column(String(32), default='database')
|
||||
kb_sync_enabled: Mapped[bool] = mapped_column(Boolean, default=False, server_default=text('false'))
|
||||
kb_group_id: Mapped[Optional[int]] = mapped_column(ForeignKey('kb_groups.id'), nullable=True, index=True)
|
||||
notify_user_ids_json: Mapped[Optional[list]] = mapped_column(JSON, default=[])
|
||||
notify_enabled: Mapped[bool] = mapped_column(Boolean, default=True)
|
||||
enabled: Mapped[bool] = mapped_column(Boolean, default=True, index=True)
|
||||
next_run_at: Mapped[Optional[datetime]] = mapped_column(DateTime, index=True)
|
||||
last_run_at: Mapped[Optional[datetime]] = mapped_column(DateTime, index=True)
|
||||
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'))
|
||||
updated_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'))
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
owner: Mapped[Optional["User"]] = relationship("User", foreign_keys=[owner_user_id])
|
||||
dify_agent: Mapped[Optional["Agent"]] = relationship("Agent", foreign_keys=[dify_agent_id])
|
||||
kb_group: Mapped[Optional["KbGroup"]] = relationship("KbGroup", foreign_keys=[kb_group_id])
|
||||
config: Mapped[Optional["ScheduleTaskConfig"]] = relationship("ScheduleTaskConfig", back_populates="task", uselist=False, cascade="all, delete-orphan")
|
||||
|
||||
|
||||
class ScheduleTaskConfig(Base):
|
||||
__tablename__ = 'schedule_task_configs'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('schedule_task_id'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
schedule_task_id: Mapped[int] = mapped_column(ForeignKey('schedule_tasks.id'), index=True)
|
||||
|
||||
row_id_key: Mapped[str] = mapped_column(String(64), default='id')
|
||||
log_prefix: Mapped[str] = mapped_column(String(128), default='')
|
||||
|
||||
base_fetch_sql: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
fetch_where_conditions: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
fetch_order_by: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)
|
||||
writeback_sql: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
detail_sql: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
alias_order: Mapped[Optional[list]] = mapped_column(JSON, default=[])
|
||||
detail_alias_order: Mapped[Optional[list]] = mapped_column(JSON, default=[])
|
||||
header_labels: Mapped[Optional[dict]] = mapped_column(JSON, default={})
|
||||
|
||||
ds_db_type: Mapped[str] = mapped_column(String(32), default='sqlserver')
|
||||
ds_host: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
ds_port: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
ds_database: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
ds_username: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
ds_password: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
ds_driver: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
ds_encrypt: Mapped[Optional[str]] = mapped_column(String(16), nullable=True)
|
||||
ds_trust_cert: Mapped[Optional[str]] = mapped_column(String(16), nullable=True)
|
||||
|
||||
api_url: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)
|
||||
api_method: Mapped[str] = mapped_column(String(16), default='POST')
|
||||
api_headers: Mapped[Optional[dict]] = mapped_column(JSON, default={})
|
||||
api_body_template: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
dify_system_prompt: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
task: Mapped[Optional["ScheduleTask"]] = relationship("ScheduleTask", back_populates="config")
|
||||
|
||||
|
||||
class ScheduleRun(Base):
|
||||
__tablename__ = 'schedule_runs'
|
||||
__table_args__ = (
|
||||
Index('ix_schedule_runs_task_created', 'schedule_task_id', 'created_at'),
|
||||
Index('ix_schedule_runs_status_created', 'status', 'created_at'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
run_no: Mapped[str] = mapped_column(String(64), unique=True, index=True)
|
||||
schedule_task_id: Mapped[int] = mapped_column(ForeignKey('schedule_tasks.id'), index=True)
|
||||
trigger_type: Mapped[str] = mapped_column(String(16), default='cron')
|
||||
triggered_by_user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'))
|
||||
started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, index=True)
|
||||
finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime, index=True)
|
||||
duration_ms: Mapped[int] = mapped_column(Integer, default=0)
|
||||
status: Mapped[str] = mapped_column(String(32), default='queued', index=True)
|
||||
total_count: Mapped[int] = mapped_column(Integer, default=0)
|
||||
success_count: Mapped[int] = mapped_column(Integer, default=0)
|
||||
failed_count: Mapped[int] = mapped_column(Integer, default=0)
|
||||
skipped_count: Mapped[int] = mapped_column(Integer, default=0)
|
||||
api_request_json: Mapped[Optional[dict]] = mapped_column(JSON)
|
||||
api_response_json: Mapped[Optional[dict]] = mapped_column(JSON)
|
||||
response_summary_json: Mapped[Optional[dict]] = mapped_column(JSON)
|
||||
step_logs: Mapped[Optional[list]] = mapped_column(JSON)
|
||||
dify_execution_snapshot: Mapped[Optional[dict]] = mapped_column(JSON)
|
||||
error_message: Mapped[Optional[str]] = mapped_column(Text)
|
||||
excel_file_data: Mapped[Optional[bytes]] = mapped_column(LargeBinary)
|
||||
excel_file_name: Mapped[Optional[str]] = mapped_column(String(255))
|
||||
excel_file_size: Mapped[Optional[int]] = mapped_column(Integer)
|
||||
kb_sync_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
kb_group_id: Mapped[Optional[int]] = mapped_column(ForeignKey('kb_groups.id'), nullable=True)
|
||||
kb_document_id: Mapped[Optional[int]] = mapped_column(ForeignKey('kb_documents.id'), nullable=True)
|
||||
kb_document_version_id: Mapped[Optional[int]] = mapped_column(ForeignKey('kb_document_versions.id'), nullable=True)
|
||||
kb_sync_job_id: Mapped[Optional[int]] = mapped_column(ForeignKey('kb_jobs.id'), nullable=True)
|
||||
kb_sync_error: Mapped[Optional[str]] = mapped_column(Text)
|
||||
wecom_notified: Mapped[bool] = mapped_column(Boolean, default=False, server_default=text('false'))
|
||||
wecom_notified_at: Mapped[Optional[datetime]] = mapped_column(DateTime)
|
||||
wecom_notify_error: Mapped[Optional[str]] = mapped_column(Text)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
|
||||
task: Mapped[Optional["ScheduleTask"]] = relationship("ScheduleTask", foreign_keys=[schedule_task_id])
|
||||
kb_group: Mapped[Optional["KbGroup"]] = relationship("KbGroup", foreign_keys=[kb_group_id])
|
||||
kb_document: Mapped[Optional["KbDocument"]] = relationship("KbDocument", foreign_keys=[kb_document_id])
|
||||
kb_document_version: Mapped[Optional["KbDocumentVersion"]] = relationship("KbDocumentVersion", foreign_keys=[kb_document_version_id])
|
||||
kb_sync_job: Mapped[Optional["KbJob"]] = relationship("KbJob", foreign_keys=[kb_sync_job_id])
|
||||
|
||||
|
||||
class ShippingBatch(Base):
|
||||
"""货代发货通知批次(一次多文件上传的聚合容器)"""
|
||||
__tablename__ = 'shipping_batches'
|
||||
__table_args__ = (
|
||||
Index('ix_shipping_batches_user_created', 'user_id', 'created_at'),
|
||||
Index('ix_shipping_batches_conversation', 'conversation_id'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
batch_no: Mapped[str] = mapped_column(String(64), unique=True, index=True)
|
||||
user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), index=True, nullable=True)
|
||||
conversation_id: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
|
||||
current_focus_task_no: Mapped[Optional[str]] = mapped_column(
|
||||
String(64),
|
||||
ForeignKey(
|
||||
'shipping_tasks.task_no',
|
||||
name='fk_shipping_batches_current_focus_task_no_shipping_tasks',
|
||||
use_alter=True,
|
||||
),
|
||||
nullable=True,
|
||||
)
|
||||
file_count: Mapped[int] = mapped_column(Integer, default=1)
|
||||
process_summary_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
tasks: Mapped[List["ShippingTask"]] = relationship(
|
||||
"ShippingTask",
|
||||
back_populates="batch",
|
||||
foreign_keys="ShippingTask.batch_id",
|
||||
)
|
||||
|
||||
|
||||
class ShippingTask(Base):
|
||||
"""货代发货通知 task(Chatflow Tool 编排状态机)"""
|
||||
__tablename__ = 'shipping_tasks'
|
||||
__table_args__ = (
|
||||
Index('ix_shipping_tasks_user_status', 'user_id', 'process_status'),
|
||||
Index('ix_shipping_tasks_conversation', 'conversation_id'),
|
||||
Index('ix_shipping_tasks_batch_step', 'batch_id', 'current_step'),
|
||||
Index('ix_shipping_tasks_upload_status', 'upload_status'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
task_no: Mapped[str] = mapped_column(String(64), unique=True, index=True)
|
||||
batch_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_batches.id'), index=True, nullable=True)
|
||||
user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), index=True, nullable=True)
|
||||
conversation_id: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
|
||||
source_type: Mapped[str] = mapped_column(String(32), default='manual')
|
||||
source_file_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
source_file_type: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
batch_index: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
|
||||
batch_total: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
|
||||
|
||||
raw_content: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
customer_name: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
|
||||
customer_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
ship_to: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
po_number: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
required_date: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
lines_json: Mapped[Optional[list]] = mapped_column(JSON, default=list)
|
||||
parse_confidence: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
|
||||
|
||||
process_status: Mapped[str] = mapped_column(String(32), default='created', index=True)
|
||||
current_step: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
review_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
match_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
shortage_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
|
||||
line_results_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
||||
inventory_snapshot_id: Mapped[Optional[int]] = mapped_column(nullable=True)
|
||||
inventory_lines_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
||||
|
||||
export_file_path: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)
|
||||
export_file_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
export_version: Mapped[int] = mapped_column(Integer, default=1)
|
||||
freight_ref_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
upload_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
upload_mode: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
upload_attempt: Mapped[int] = mapped_column(Integer, default=0)
|
||||
idempotency_key: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
upload_started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
upload_finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
upload_error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
upload_error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
upload_receipt_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
|
||||
step_payload_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
|
||||
pending_human_reason: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
batch: Mapped[Optional["ShippingBatch"]] = relationship(
|
||||
"ShippingBatch",
|
||||
back_populates="tasks",
|
||||
foreign_keys=[batch_id],
|
||||
)
|
||||
events: Mapped[List["ShippingTaskEvent"]] = relationship(
|
||||
"ShippingTaskEvent",
|
||||
back_populates="task",
|
||||
cascade="all, delete-orphan",
|
||||
)
|
||||
|
||||
|
||||
class ShippingTaskEvent(Base):
|
||||
"""发货 task 审计事件"""
|
||||
__tablename__ = 'shipping_task_events'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_tasks.id'), index=True)
|
||||
event_type: Mapped[str] = mapped_column(String(64), index=True)
|
||||
detail_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
|
||||
task: Mapped["ShippingTask"] = relationship("ShippingTask", back_populates="events")
|
||||
|
||||
|
||||
class ShippingInventoryMapping(Base):
|
||||
"""客户库存 Excel 表头 → 标准字段的列映射缓存(按 customer_code + header_hash 去重)。"""
|
||||
__tablename__ = 'shipping_inventory_mappings'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('customer_code', 'header_hash', name='uq_shipping_inventory_mappings_customer_header'),
|
||||
Index('ix_shipping_inventory_mappings_customer_code', 'customer_code'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
customer_code: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
header_hash: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
headers_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
||||
field_mapping_json: Mapped[dict] = mapped_column(JSON, nullable=False, default=dict)
|
||||
last_used_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow, index=True)
|
||||
|
||||
class AgentGuide(Base):
|
||||
"""
|
||||
平台应用新手指南表
|
||||
用途:存储 Agent 的新手指南文件信息 (如视频、PDF)
|
||||
"""
|
||||
__tablename__ = 'agent_guides'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
agent_id: Mapped[int] = mapped_column(ForeignKey('agents.id'), index=True)
|
||||
file_name: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
file_type: Mapped[str] = mapped_column(String(50), nullable=False) # video, pdf, image
|
||||
file_path: Mapped[str] = mapped_column(String(500), nullable=False)
|
||||
file_size: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
|
||||
remark: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
sort_order: Mapped[int] = mapped_column(Integer, default=0)
|
||||
status: Mapped[int] = mapped_column(Integer, default=1) # 1: 启用, 0: 禁用
|
||||
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
agent: Mapped[Optional["Agent"]] = relationship("Agent", foreign_keys=[agent_id])
|
||||
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
"""
|
||||
backend/app/models/__init__.py
|
||||
|
||||
用途:按业务域拆分的 ORM 模型包入口;聚合导出以保持 `from app.models import User` 兼容。
|
||||
依赖:models/* 子模块、app.extensions.db(经 base.Base)。
|
||||
逻辑:Alembic / Flask-Migrate 通过本模块 import 注册全部表元数据;业务代码继续从此处导入模型类。
|
||||
"""
|
||||
|
||||
from app.models.agent import Agent, AgentGuide, PermissionRequest
|
||||
from app.models.base import Base, user_agent_permissions
|
||||
from app.models.chat import ChatLog, ChatSession, Feedback, GeneralFeedback
|
||||
from app.models.content import Announcement, FaqHotCandidate, QuickQuestion, ZlLanguage
|
||||
from app.models.department import Department
|
||||
from app.models.job import Job
|
||||
from app.models.kb import KbDifySyncRecord, KbDocument, KbDocumentVersion, KbGroup, KbJob
|
||||
from app.models.schedule import ScheduleRun, ScheduleTask, ScheduleTaskConfig
|
||||
from app.models.settings import AppSetting
|
||||
from app.models.shipping import (
|
||||
ShippingBatch,
|
||||
ShippingInventoryFile,
|
||||
ShippingInventoryMapping,
|
||||
ShippingTask,
|
||||
ShippingTaskEvent,
|
||||
ShippingTaskInventoryLink,
|
||||
)
|
||||
from app.models.training import TrainingRecord
|
||||
from app.models.user import LoginAudit, User, UserDefaultAgent, UserFavoriteAgent, UserHomepageConfig
|
||||
from app.models.wecom import WecomCallbackAudit, WecomNotifyAudit
|
||||
|
||||
__all__ = [
|
||||
'Base',
|
||||
'user_agent_permissions',
|
||||
'ZlLanguage',
|
||||
'Department',
|
||||
'UserHomepageConfig',
|
||||
'UserFavoriteAgent',
|
||||
'UserDefaultAgent',
|
||||
'User',
|
||||
'Agent',
|
||||
'ChatSession',
|
||||
'ChatLog',
|
||||
'Feedback',
|
||||
'GeneralFeedback',
|
||||
'PermissionRequest',
|
||||
'QuickQuestion',
|
||||
'FaqHotCandidate',
|
||||
'Announcement',
|
||||
'LoginAudit',
|
||||
'WecomNotifyAudit',
|
||||
'AppSetting',
|
||||
'KbGroup',
|
||||
'KbDocument',
|
||||
'KbDocumentVersion',
|
||||
'KbJob',
|
||||
'Job',
|
||||
'KbDifySyncRecord',
|
||||
'WecomCallbackAudit',
|
||||
'ScheduleTask',
|
||||
'ScheduleTaskConfig',
|
||||
'ScheduleRun',
|
||||
'ShippingBatch',
|
||||
'ShippingTask',
|
||||
'ShippingTaskEvent',
|
||||
'ShippingInventoryFile',
|
||||
'ShippingTaskInventoryLink',
|
||||
'ShippingInventoryMapping',
|
||||
'AgentGuide',
|
||||
'TrainingRecord',
|
||||
]
|
||||
@@ -0,0 +1,84 @@
|
||||
"""
|
||||
backend/app/models/agent.py
|
||||
|
||||
用途:Dify Agent 配置、新手指南、权限申请模型。
|
||||
依赖:models.base(Base、user_agent_permissions)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import List, Optional
|
||||
|
||||
from sqlalchemy import DateTime, ForeignKey, Integer, JSON, String, Text
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from app.models.base import Base, user_agent_permissions
|
||||
|
||||
|
||||
class Agent(Base):
|
||||
"""
|
||||
AI 应用配置表
|
||||
用途:存储接入的 Dify Agent 配置信息
|
||||
核心逻辑:存储 Dify App ID 和 API Key,控制应用开关
|
||||
"""
|
||||
|
||||
__tablename__ = 'agents'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
name: Mapped[str] = mapped_column(String(100))
|
||||
description: Mapped[Optional[str]] = mapped_column(Text)
|
||||
icon_url: Mapped[Optional[str]] = mapped_column(String(255))
|
||||
dify_app_id: Mapped[Optional[str]] = mapped_column(String(100), unique=True, nullable=True)
|
||||
dify_api_key: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
|
||||
type: Mapped[str] = mapped_column(String(20), default='api')
|
||||
api_base_url: Mapped[Optional[str]] = mapped_column(String(255))
|
||||
extra_config: Mapped[Optional[dict]] = mapped_column(JSON)
|
||||
is_active: Mapped[bool] = mapped_column(default=True)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
|
||||
users: Mapped[List['User']] = relationship(
|
||||
secondary=user_agent_permissions,
|
||||
back_populates='agents',
|
||||
)
|
||||
|
||||
|
||||
class AgentGuide(Base):
|
||||
"""
|
||||
平台应用新手指南表
|
||||
用途:存储 Agent 的新手指南文件信息 (如视频、PDF)
|
||||
"""
|
||||
|
||||
__tablename__ = 'agent_guides'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
agent_id: Mapped[int] = mapped_column(ForeignKey('agents.id'), index=True)
|
||||
file_name: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
file_type: Mapped[str] = mapped_column(String(50), nullable=False)
|
||||
file_path: Mapped[str] = mapped_column(String(500), nullable=False)
|
||||
file_size: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
|
||||
remark: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
sort_order: Mapped[int] = mapped_column(Integer, default=0)
|
||||
status: Mapped[int] = mapped_column(Integer, default=1)
|
||||
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
agent: Mapped[Optional['Agent']] = relationship('Agent', foreign_keys=[agent_id])
|
||||
|
||||
|
||||
class PermissionRequest(Base):
|
||||
"""
|
||||
权限申请表
|
||||
用途:存储用户的权限申请记录
|
||||
"""
|
||||
|
||||
__tablename__ = 'permission_requests'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
user_id: Mapped[int] = mapped_column(ForeignKey('users.id'))
|
||||
agent_id: Mapped[int] = mapped_column(ForeignKey('agents.id'))
|
||||
reason: Mapped[str] = mapped_column(Text)
|
||||
status: Mapped[str] = mapped_column(String(20), default='pending')
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
reviewed_at: Mapped[Optional[datetime]] = mapped_column(DateTime)
|
||||
@@ -0,0 +1,27 @@
|
||||
"""
|
||||
backend/app/models/base.py
|
||||
|
||||
用途:SQLAlchemy 抽象基类与用户-Agent RBAC 关联表。
|
||||
依赖:app.extensions.db。
|
||||
逻辑:各域 model 模块继承 Base;User.agents / Agent.users 共用 user_agent_permissions。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from sqlalchemy import ForeignKey
|
||||
|
||||
from app.extensions import db
|
||||
|
||||
|
||||
class Base(db.Model):
|
||||
"""抽象基类,所有业务模型继承此类。"""
|
||||
|
||||
__abstract__ = True
|
||||
|
||||
|
||||
# RBAC 关联表:用户与 Agent 的多对多关系
|
||||
user_agent_permissions = db.Table(
|
||||
'user_agent_permissions',
|
||||
db.Column('user_id', ForeignKey('users.id'), primary_key=True),
|
||||
db.Column('agent_id', ForeignKey('agents.id'), primary_key=True),
|
||||
)
|
||||
@@ -0,0 +1,102 @@
|
||||
"""
|
||||
backend/app/models/chat.py
|
||||
|
||||
用途:对话会话、消息日志与反馈模型。
|
||||
依赖:models.base.Base。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy import DateTime, ForeignKey, Index, Integer, JSON, String, Text
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
class ChatSession(Base):
|
||||
"""
|
||||
聊天会话表
|
||||
用途:独立持久化会话元数据,使生成中会话也能立即出现在历史记录中
|
||||
"""
|
||||
|
||||
__tablename__ = 'chat_sessions'
|
||||
__table_args__ = (
|
||||
Index('ix_chat_sessions_user_agent_last_active', 'user_id', 'agent_id', 'last_active_at'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
session_id: Mapped[str] = mapped_column(String(100), unique=True, index=True)
|
||||
user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), index=True)
|
||||
agent_id: Mapped[int] = mapped_column(ForeignKey('agents.id'), index=True)
|
||||
title: Mapped[str] = mapped_column(String(255), default='')
|
||||
status: Mapped[str] = mapped_column(String(20), default='running')
|
||||
external_conversation_id: Mapped[Optional[str]] = mapped_column(String(100), index=True, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
last_active_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
|
||||
|
||||
class ChatLog(Base):
|
||||
"""
|
||||
对话日志表
|
||||
用途:存储用户与 Agent 的对话记录
|
||||
"""
|
||||
|
||||
__tablename__ = 'chat_logs'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
user_id: Mapped[int] = mapped_column(ForeignKey('users.id'))
|
||||
agent_id: Mapped[int] = mapped_column(ForeignKey('agents.id'))
|
||||
query: Mapped[str] = mapped_column(Text)
|
||||
answer: Mapped[str] = mapped_column(Text)
|
||||
latency: Mapped[int] = mapped_column(default=0)
|
||||
conversation_id: Mapped[Optional[str]] = mapped_column(String(100))
|
||||
session_id: Mapped[Optional[str]] = mapped_column(String(100), index=True, nullable=True)
|
||||
run_id: Mapped[Optional[int]] = mapped_column(ForeignKey('schedule_runs.id'), index=True, nullable=True)
|
||||
message_type: Mapped[Optional[str]] = mapped_column(String(50), nullable=True)
|
||||
payload: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
|
||||
tokens_used: Mapped[int] = mapped_column(default=0)
|
||||
retriever_resources: Mapped[Optional[list]] = mapped_column(JSON)
|
||||
attribution_parts: Mapped[Optional[list]] = mapped_column(JSON)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
|
||||
feedback: Mapped[Optional['Feedback']] = relationship(back_populates='chat_log', uselist=False)
|
||||
|
||||
|
||||
class Feedback(Base):
|
||||
"""
|
||||
反馈表
|
||||
用途:存储用户对回答的评分与评价
|
||||
"""
|
||||
|
||||
__tablename__ = 'feedbacks'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
chat_log_id: Mapped[int] = mapped_column(ForeignKey('chat_logs.id'), unique=True)
|
||||
score: Mapped[int] = mapped_column(Integer)
|
||||
comment: Mapped[Optional[str]] = mapped_column(Text)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
|
||||
chat_log: Mapped['ChatLog'] = relationship(back_populates='feedback')
|
||||
|
||||
|
||||
class GeneralFeedback(Base):
|
||||
"""
|
||||
通用意见反馈表
|
||||
用于存储 Workspace/Chat 页面提交的通用意见反馈
|
||||
"""
|
||||
|
||||
__tablename__ = 'general_feedbacks'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), index=True)
|
||||
chat_log_id: Mapped[Optional[int]] = mapped_column(ForeignKey('chat_logs.id'), nullable=True, index=True)
|
||||
username: Mapped[str] = mapped_column(String(50), nullable=False)
|
||||
feedback_type: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
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))
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
@@ -0,0 +1,109 @@
|
||||
"""
|
||||
backend/app/models/content.py
|
||||
|
||||
用途:多语言、常用问题、热点 FAQ 候选、公告等内容模型。
|
||||
依赖:models.base.Base。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy import Boolean, DateTime, Float, ForeignKey, Index, JSON, String, Text, UniqueConstraint
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
class ZlLanguage(Base):
|
||||
"""
|
||||
多语言配置表
|
||||
用途:存储系统支持的语言列表
|
||||
"""
|
||||
|
||||
__tablename__ = 'zl_languages'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
code: Mapped[str] = mapped_column(String(10), unique=True)
|
||||
name: Mapped[str] = mapped_column(String(50))
|
||||
is_active: Mapped[bool] = mapped_column(default=True)
|
||||
|
||||
|
||||
class QuickQuestion(Base):
|
||||
"""
|
||||
常用问题表
|
||||
用途:存储全局/用户常用问题;全局条目(user_id 为空)可配置标准答案并启用 FAQ 缓存命中。
|
||||
"""
|
||||
|
||||
__tablename__ = 'quick_questions'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
agent_id: Mapped[int] = mapped_column(ForeignKey('agents.id'))
|
||||
title: Mapped[str] = mapped_column(String(100))
|
||||
question: Mapped[str] = mapped_column(Text)
|
||||
answer: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
aliases: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
||||
cache_enabled: Mapped[bool] = mapped_column(default=False)
|
||||
is_enabled: Mapped[bool] = mapped_column(default=True)
|
||||
hit_count: Mapped[int] = mapped_column(default=0)
|
||||
retriever_resources: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
||||
source_kb_document_ids: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
||||
expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
stale_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
stale_reason: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
stale_kb_document_id: Mapped[Optional[int]] = mapped_column(ForeignKey('kb_documents.id'), nullable=True)
|
||||
sort_order: Mapped[int] = mapped_column(default=0)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
|
||||
class FaqHotCandidate(Base):
|
||||
"""
|
||||
热点 FAQ 候选表
|
||||
用途:离线聚合 ChatLog 后的待审核热点问句与推荐答案(PostgreSQL 存储,不含在线命中)。
|
||||
"""
|
||||
|
||||
__tablename__ = 'faq_hot_candidates'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('agent_id', 'q_norm', name='uq_faq_hot_candidates_agent_qnorm'),
|
||||
Index('ix_faq_hot_candidates_status_expires', 'status', 'expires_at'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
agent_id: Mapped[int] = mapped_column(ForeignKey('agents.id'), index=True)
|
||||
q_norm: Mapped[str] = mapped_column(String(255))
|
||||
canonical_query: Mapped[str] = mapped_column(Text)
|
||||
answer: Mapped[str] = mapped_column(Text)
|
||||
source_chat_log_id: Mapped[Optional[int]] = mapped_column(ForeignKey('chat_logs.id'), nullable=True)
|
||||
ask_count_7d: Mapped[int] = mapped_column(default=0)
|
||||
user_count_7d: Mapped[int] = mapped_column(default=0)
|
||||
avg_tokens: Mapped[int] = mapped_column(default=0)
|
||||
avg_latency_ms: Mapped[int] = mapped_column(default=0)
|
||||
answer_dominance: Mapped[float] = mapped_column(default=0.0)
|
||||
sample_queries: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
||||
retriever_resources: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
||||
last_asked_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
status: Mapped[str] = mapped_column(String(20), default='candidate')
|
||||
promoted_quick_question_id: Mapped[Optional[int]] = mapped_column(ForeignKey('quick_questions.id'), nullable=True)
|
||||
deny_until: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
|
||||
class Announcement(Base):
|
||||
"""
|
||||
公告表
|
||||
用途:存储系统公告
|
||||
"""
|
||||
|
||||
__tablename__ = 'announcements'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
title: Mapped[str] = mapped_column(String(200))
|
||||
content: Mapped[str] = mapped_column(Text)
|
||||
is_active: Mapped[bool] = mapped_column(default=True)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
@@ -0,0 +1,27 @@
|
||||
"""
|
||||
backend/app/models/department.py
|
||||
|
||||
用途:部门组织模型。
|
||||
依赖:models.base.Base。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy import String, Text
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
class Department(Base):
|
||||
"""部门表:存储公司部门列表。"""
|
||||
|
||||
__tablename__ = 'departments'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
name: Mapped[str] = mapped_column(String(100), unique=True)
|
||||
code: Mapped[Optional[str]] = mapped_column(String(50), unique=True)
|
||||
company: Mapped[Optional[str]] = mapped_column(String(100))
|
||||
description: Mapped[Optional[str]] = mapped_column(Text)
|
||||
@@ -0,0 +1,55 @@
|
||||
"""
|
||||
backend/app/models/job.py
|
||||
|
||||
用途:通用后台任务模型,承载跨业务域的异步任务执行状态。
|
||||
依赖:models.base.Base。
|
||||
逻辑:由 app.jobs.queue 写入和领取,由 worker 分发到具体业务 handler;业务模型保存业务状态,本表保存执行状态、锁、重试与结果。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy import DateTime, ForeignKey, Index, Integer, JSON, String, Text
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
class Job(Base):
|
||||
"""
|
||||
通用后台任务
|
||||
用途:承载非知识库专属的后台任务队列与执行记录
|
||||
"""
|
||||
|
||||
__tablename__ = 'jobs'
|
||||
__table_args__ = (
|
||||
Index('ix_jobs_domain_status_created', 'domain', 'status', 'created_at'),
|
||||
Index('ix_jobs_type_status_created', 'job_type', 'status', 'created_at'),
|
||||
Index('ix_jobs_business_ref', 'domain', 'job_type', 'business_ref'),
|
||||
Index('ix_jobs_locked_at', 'locked_at'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
domain: Mapped[str] = mapped_column(String(64), index=True)
|
||||
job_type: Mapped[str] = mapped_column(String(64), index=True)
|
||||
status: Mapped[str] = mapped_column(String(32), default='queued', index=True)
|
||||
priority: Mapped[int] = mapped_column(Integer, default=0, index=True)
|
||||
business_ref: Mapped[Optional[str]] = mapped_column(String(128))
|
||||
payload_json: Mapped[Optional[dict]] = mapped_column(JSON)
|
||||
result_json: Mapped[Optional[dict]] = mapped_column(JSON)
|
||||
progress: Mapped[int] = mapped_column(Integer, default=0)
|
||||
message: Mapped[Optional[str]] = mapped_column(Text)
|
||||
error_message: Mapped[Optional[str]] = mapped_column(Text)
|
||||
attempts: Mapped[int] = mapped_column(Integer, default=0)
|
||||
max_attempts: Mapped[int] = mapped_column(Integer, default=3)
|
||||
locked_by: Mapped[Optional[str]] = mapped_column(String(128))
|
||||
locked_at: Mapped[Optional[datetime]] = mapped_column(DateTime)
|
||||
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'))
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
started_at: Mapped[Optional[datetime]] = mapped_column(DateTime)
|
||||
finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime)
|
||||
|
||||
created_by: Mapped[Optional['User']] = relationship('User', foreign_keys=[created_by_id])
|
||||
@@ -0,0 +1,206 @@
|
||||
"""
|
||||
backend/app/models/kb.py
|
||||
|
||||
用途:知识库分组、文档、版本、任务与 Dify 同步记录。
|
||||
依赖:models.base.Base。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import List, Optional
|
||||
|
||||
from sqlalchemy import Boolean, DateTime, ForeignKey, Index, Integer, JSON, String, Text, UniqueConstraint
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
class KbGroup(Base):
|
||||
"""
|
||||
知识库分组
|
||||
用途:承载数据清洗/知识库管理模块中的分组/知识库
|
||||
"""
|
||||
|
||||
__tablename__ = 'kb_groups'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('department_id', 'name', name='uq_kb_groups_department_name'),
|
||||
Index('ix_kb_groups_department_active', 'department_id', 'is_active'),
|
||||
Index('ix_kb_groups_dify_dataset_id', 'dify_dataset_id'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
name: Mapped[str] = mapped_column(String(128), index=True)
|
||||
description: Mapped[Optional[str]] = mapped_column(Text)
|
||||
department_id: Mapped[Optional[int]] = mapped_column(Integer, nullable=True, index=True)
|
||||
is_active: Mapped[bool] = mapped_column(Boolean, default=True)
|
||||
dify_dataset_id: Mapped[Optional[str]] = mapped_column(String(128))
|
||||
dify_dataset_name: Mapped[Optional[str]] = mapped_column(String(255))
|
||||
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'))
|
||||
updated_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'))
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
created_by: Mapped[Optional['User']] = relationship('User', foreign_keys=[created_by_id])
|
||||
updated_by: Mapped[Optional['User']] = relationship('User', foreign_keys=[updated_by_id])
|
||||
documents: Mapped[List['KbDocument']] = relationship(
|
||||
'KbDocument',
|
||||
back_populates='group',
|
||||
cascade='all, delete-orphan',
|
||||
)
|
||||
|
||||
|
||||
class KbDocument(Base):
|
||||
"""
|
||||
知识库逻辑文档
|
||||
用途:表示一个文档条目,不直接等同于某一次上传文件
|
||||
"""
|
||||
|
||||
__tablename__ = 'kb_documents'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('group_id', 'title', name='uq_kb_documents_group_title'),
|
||||
Index('ix_kb_documents_group_status', 'group_id', 'status'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
group_id: Mapped[int] = mapped_column(ForeignKey('kb_groups.id'), index=True)
|
||||
title: Mapped[str] = mapped_column(String(255))
|
||||
description: Mapped[Optional[str]] = mapped_column(Text)
|
||||
status: Mapped[str] = mapped_column(String(32), default='draft', index=True)
|
||||
source_type: Mapped[Optional[str]] = mapped_column(String(32))
|
||||
is_deleted: Mapped[bool] = mapped_column(Boolean, default=False, index=True)
|
||||
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'))
|
||||
updated_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'))
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
group: Mapped['KbGroup'] = relationship('KbGroup', back_populates='documents')
|
||||
created_by: Mapped[Optional['User']] = relationship('User', foreign_keys=[created_by_id])
|
||||
updated_by: Mapped[Optional['User']] = relationship('User', foreign_keys=[updated_by_id])
|
||||
versions: Mapped[List['KbDocumentVersion']] = relationship(
|
||||
'KbDocumentVersion',
|
||||
back_populates='document',
|
||||
cascade='all, delete-orphan',
|
||||
order_by='desc(KbDocumentVersion.version_no)',
|
||||
)
|
||||
|
||||
|
||||
class KbDocumentVersion(Base):
|
||||
"""
|
||||
知识库文档版本
|
||||
用途:记录每次上传、清洗、同步产生的版本信息
|
||||
"""
|
||||
|
||||
__tablename__ = 'kb_document_versions'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('document_id', 'version_no', name='uq_kb_document_versions_doc_version'),
|
||||
Index('ix_kb_document_versions_doc_status', 'document_id', 'status'),
|
||||
Index('ix_kb_document_versions_sha256', 'sha256'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
document_id: Mapped[int] = mapped_column(ForeignKey('kb_documents.id'), index=True)
|
||||
version_no: Mapped[int] = mapped_column(Integer)
|
||||
status: Mapped[str] = mapped_column(String(32), default='uploaded', index=True)
|
||||
is_current: Mapped[bool] = mapped_column(Boolean, default=True, index=True)
|
||||
source_file_name: Mapped[str] = mapped_column(String(255))
|
||||
source_file_path: Mapped[str] = mapped_column(Text)
|
||||
source_file_ext: Mapped[Optional[str]] = mapped_column(String(32))
|
||||
source_file_size: Mapped[Optional[int]] = mapped_column(Integer)
|
||||
cleaned_file_path: Mapped[Optional[str]] = mapped_column(Text)
|
||||
cleaned_preview_path: Mapped[Optional[str]] = mapped_column(Text)
|
||||
sha256: Mapped[Optional[str]] = mapped_column(String(64))
|
||||
word_count: Mapped[int] = mapped_column(Integer, default=0)
|
||||
error_message: Mapped[Optional[str]] = mapped_column(Text)
|
||||
warnings_json: Mapped[Optional[dict]] = mapped_column(JSON)
|
||||
uploaded_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'))
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
converted_at: Mapped[Optional[datetime]] = mapped_column(DateTime)
|
||||
|
||||
document: Mapped['KbDocument'] = relationship('KbDocument', back_populates='versions')
|
||||
uploaded_by: Mapped[Optional['User']] = relationship('User', foreign_keys=[uploaded_by_id])
|
||||
jobs: Mapped[List['KbJob']] = relationship(
|
||||
'KbJob',
|
||||
back_populates='document_version',
|
||||
cascade='all, delete-orphan',
|
||||
)
|
||||
sync_records: Mapped[List['KbDifySyncRecord']] = relationship(
|
||||
'KbDifySyncRecord',
|
||||
back_populates='document_version',
|
||||
cascade='all, delete-orphan',
|
||||
order_by='desc(KbDifySyncRecord.updated_at)',
|
||||
)
|
||||
|
||||
|
||||
class KbJob(Base):
|
||||
"""
|
||||
知识库后台任务
|
||||
用途:记录上传、清洗、同步等后台任务执行情况
|
||||
"""
|
||||
|
||||
__tablename__ = 'kb_jobs'
|
||||
__table_args__ = (
|
||||
Index('ix_kb_jobs_status_created', 'status', 'created_at'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
job_type: Mapped[str] = mapped_column(String(32), index=True)
|
||||
status: Mapped[str] = mapped_column(String(32), default='queued', index=True)
|
||||
queue_job_id: Mapped[Optional[str]] = mapped_column(String(64))
|
||||
group_id: Mapped[Optional[int]] = mapped_column(ForeignKey('kb_groups.id'))
|
||||
document_id: Mapped[Optional[int]] = mapped_column(ForeignKey('kb_documents.id'))
|
||||
document_version_id: Mapped[Optional[int]] = mapped_column(ForeignKey('kb_document_versions.id'), index=True)
|
||||
progress: Mapped[int] = mapped_column(Integer, default=0)
|
||||
message: Mapped[Optional[str]] = mapped_column(Text)
|
||||
error_message: Mapped[Optional[str]] = mapped_column(Text)
|
||||
payload_json: Mapped[Optional[dict]] = mapped_column(JSON)
|
||||
result_json: Mapped[Optional[dict]] = mapped_column(JSON)
|
||||
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'))
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
started_at: Mapped[Optional[datetime]] = mapped_column(DateTime)
|
||||
finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime)
|
||||
|
||||
created_by: Mapped[Optional['User']] = relationship('User', foreign_keys=[created_by_id])
|
||||
document_version: Mapped[Optional['KbDocumentVersion']] = relationship(
|
||||
'KbDocumentVersion',
|
||||
back_populates='jobs',
|
||||
)
|
||||
|
||||
|
||||
class KbDifySyncRecord(Base):
|
||||
"""
|
||||
知识库 Dify 同步记录
|
||||
用途:记录本地文档版本与 Dify 远端文档之间的同步映射
|
||||
"""
|
||||
|
||||
__tablename__ = 'kb_dify_sync_records'
|
||||
__table_args__ = (
|
||||
UniqueConstraint(
|
||||
'document_version_id',
|
||||
'remote_document_id',
|
||||
name='uq_kb_dify_sync_records_version_remote',
|
||||
),
|
||||
Index('ix_kb_dify_sync_records_dataset_id', 'dataset_id'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
group_id: Mapped[Optional[int]] = mapped_column(ForeignKey('kb_groups.id'))
|
||||
document_id: Mapped[Optional[int]] = mapped_column(ForeignKey('kb_documents.id'))
|
||||
document_version_id: Mapped[int] = mapped_column(ForeignKey('kb_document_versions.id'), index=True)
|
||||
dataset_id: Mapped[str] = mapped_column(String(128))
|
||||
dataset_name: Mapped[Optional[str]] = mapped_column(String(255))
|
||||
remote_document_id: Mapped[str] = mapped_column(String(128))
|
||||
remote_document_name: Mapped[Optional[str]] = mapped_column(String(255))
|
||||
status: Mapped[str] = mapped_column(String(32), default='pending', index=True)
|
||||
sync_hash: Mapped[Optional[str]] = mapped_column(String(64))
|
||||
error_message: Mapped[Optional[str]] = mapped_column(Text)
|
||||
synced_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'))
|
||||
synced_at: Mapped[Optional[datetime]] = mapped_column(DateTime)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
document_version: Mapped['KbDocumentVersion'] = relationship(
|
||||
'KbDocumentVersion',
|
||||
back_populates='sync_records',
|
||||
)
|
||||
synced_by: Mapped[Optional['User']] = relationship('User', foreign_keys=[synced_by_id])
|
||||
@@ -0,0 +1,146 @@
|
||||
"""
|
||||
backend/app/models/schedule.py
|
||||
|
||||
用途:定时任务定义、配置与执行记录。
|
||||
依赖:models.base.Base;与 kb、chat 模块存在外键关联。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy import Boolean, DateTime, ForeignKey, Index, Integer, JSON, LargeBinary, String, Text, UniqueConstraint, text
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
class ScheduleTask(Base):
|
||||
__tablename__ = 'schedule_tasks'
|
||||
__table_args__ = (
|
||||
Index('ix_schedule_tasks_enabled_next_run', 'enabled', 'next_run_at'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
schedule_no: Mapped[str] = mapped_column(String(64), unique=True, index=True)
|
||||
name: Mapped[str] = mapped_column(String(128), index=True)
|
||||
schedule_type: Mapped[str] = mapped_column(String(32), default='platform_app')
|
||||
owner_user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), index=True)
|
||||
cron_expr: Mapped[str] = mapped_column(String(64))
|
||||
schedule_timezone: Mapped[str] = mapped_column(String(64), default='Asia/Shanghai', server_default=text("'Asia/Shanghai'"))
|
||||
wait_seconds: Mapped[int] = mapped_column(Integer, default=0)
|
||||
dify_agent_id: Mapped[Optional[int]] = mapped_column(ForeignKey('agents.id'), nullable=True, index=True)
|
||||
platform_api_path: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)
|
||||
data_source_type: Mapped[str] = mapped_column(String(32), default='database')
|
||||
kb_sync_enabled: Mapped[bool] = mapped_column(Boolean, default=False, server_default=text('false'))
|
||||
kb_group_id: Mapped[Optional[int]] = mapped_column(ForeignKey('kb_groups.id'), nullable=True, index=True)
|
||||
notify_user_ids_json: Mapped[Optional[list]] = mapped_column(JSON, default=[])
|
||||
notify_enabled: Mapped[bool] = mapped_column(Boolean, default=True)
|
||||
enabled: Mapped[bool] = mapped_column(Boolean, default=True, index=True)
|
||||
next_run_at: Mapped[Optional[datetime]] = mapped_column(DateTime, index=True)
|
||||
last_run_at: Mapped[Optional[datetime]] = mapped_column(DateTime, index=True)
|
||||
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'))
|
||||
updated_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'))
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
owner: Mapped[Optional['User']] = relationship('User', foreign_keys=[owner_user_id])
|
||||
dify_agent: Mapped[Optional['Agent']] = relationship('Agent', foreign_keys=[dify_agent_id])
|
||||
kb_group: Mapped[Optional['KbGroup']] = relationship('KbGroup', foreign_keys=[kb_group_id])
|
||||
config: Mapped[Optional['ScheduleTaskConfig']] = relationship(
|
||||
'ScheduleTaskConfig',
|
||||
back_populates='task',
|
||||
uselist=False,
|
||||
cascade='all, delete-orphan',
|
||||
)
|
||||
|
||||
|
||||
class ScheduleTaskConfig(Base):
|
||||
__tablename__ = 'schedule_task_configs'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('schedule_task_id'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
schedule_task_id: Mapped[int] = mapped_column(ForeignKey('schedule_tasks.id'), index=True)
|
||||
|
||||
row_id_key: Mapped[str] = mapped_column(String(64), default='id')
|
||||
log_prefix: Mapped[str] = mapped_column(String(128), default='')
|
||||
|
||||
base_fetch_sql: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
fetch_where_conditions: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
fetch_order_by: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)
|
||||
writeback_sql: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
detail_sql: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
alias_order: Mapped[Optional[list]] = mapped_column(JSON, default=[])
|
||||
detail_alias_order: Mapped[Optional[list]] = mapped_column(JSON, default=[])
|
||||
header_labels: Mapped[Optional[dict]] = mapped_column(JSON, default={})
|
||||
|
||||
ds_db_type: Mapped[str] = mapped_column(String(32), default='sqlserver')
|
||||
ds_host: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
ds_port: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
ds_database: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
ds_username: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
ds_password: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
ds_driver: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
ds_encrypt: Mapped[Optional[str]] = mapped_column(String(16), nullable=True)
|
||||
ds_trust_cert: Mapped[Optional[str]] = mapped_column(String(16), nullable=True)
|
||||
|
||||
api_url: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)
|
||||
api_method: Mapped[str] = mapped_column(String(16), default='POST')
|
||||
api_headers: Mapped[Optional[dict]] = mapped_column(JSON, default={})
|
||||
api_body_template: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
dify_system_prompt: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
task: Mapped[Optional['ScheduleTask']] = relationship('ScheduleTask', back_populates='config')
|
||||
|
||||
|
||||
class ScheduleRun(Base):
|
||||
__tablename__ = 'schedule_runs'
|
||||
__table_args__ = (
|
||||
Index('ix_schedule_runs_task_created', 'schedule_task_id', 'created_at'),
|
||||
Index('ix_schedule_runs_status_created', 'status', 'created_at'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
run_no: Mapped[str] = mapped_column(String(64), unique=True, index=True)
|
||||
schedule_task_id: Mapped[int] = mapped_column(ForeignKey('schedule_tasks.id'), index=True)
|
||||
trigger_type: Mapped[str] = mapped_column(String(16), default='cron')
|
||||
triggered_by_user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'))
|
||||
started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, index=True)
|
||||
finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime, index=True)
|
||||
duration_ms: Mapped[int] = mapped_column(Integer, default=0)
|
||||
status: Mapped[str] = mapped_column(String(32), default='queued', index=True)
|
||||
total_count: Mapped[int] = mapped_column(Integer, default=0)
|
||||
success_count: Mapped[int] = mapped_column(Integer, default=0)
|
||||
failed_count: Mapped[int] = mapped_column(Integer, default=0)
|
||||
skipped_count: Mapped[int] = mapped_column(Integer, default=0)
|
||||
api_request_json: Mapped[Optional[dict]] = mapped_column(JSON)
|
||||
api_response_json: Mapped[Optional[dict]] = mapped_column(JSON)
|
||||
response_summary_json: Mapped[Optional[dict]] = mapped_column(JSON)
|
||||
step_logs: Mapped[Optional[list]] = mapped_column(JSON)
|
||||
dify_execution_snapshot: Mapped[Optional[dict]] = mapped_column(JSON)
|
||||
error_message: Mapped[Optional[str]] = mapped_column(Text)
|
||||
excel_file_data: Mapped[Optional[bytes]] = mapped_column(LargeBinary)
|
||||
excel_file_name: Mapped[Optional[str]] = mapped_column(String(255))
|
||||
excel_file_size: Mapped[Optional[int]] = mapped_column(Integer)
|
||||
kb_sync_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
kb_group_id: Mapped[Optional[int]] = mapped_column(ForeignKey('kb_groups.id'), nullable=True)
|
||||
kb_document_id: Mapped[Optional[int]] = mapped_column(ForeignKey('kb_documents.id'), nullable=True)
|
||||
kb_document_version_id: Mapped[Optional[int]] = mapped_column(ForeignKey('kb_document_versions.id'), nullable=True)
|
||||
kb_sync_job_id: Mapped[Optional[int]] = mapped_column(ForeignKey('kb_jobs.id'), nullable=True)
|
||||
kb_sync_error: Mapped[Optional[str]] = mapped_column(Text)
|
||||
wecom_notified: Mapped[bool] = mapped_column(Boolean, default=False, server_default=text('false'))
|
||||
wecom_notified_at: Mapped[Optional[datetime]] = mapped_column(DateTime)
|
||||
wecom_notify_error: Mapped[Optional[str]] = mapped_column(Text)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
|
||||
task: Mapped[Optional['ScheduleTask']] = relationship('ScheduleTask', foreign_keys=[schedule_task_id])
|
||||
kb_group: Mapped[Optional['KbGroup']] = relationship('KbGroup', foreign_keys=[kb_group_id])
|
||||
kb_document: Mapped[Optional['KbDocument']] = relationship('KbDocument', foreign_keys=[kb_document_id])
|
||||
kb_document_version: Mapped[Optional['KbDocumentVersion']] = relationship('KbDocumentVersion', foreign_keys=[kb_document_version_id])
|
||||
kb_sync_job: Mapped[Optional['KbJob']] = relationship('KbJob', foreign_keys=[kb_sync_job_id])
|
||||
@@ -0,0 +1,32 @@
|
||||
"""
|
||||
backend/app/models/settings.py
|
||||
|
||||
用途:应用运行时 Key/Value 配置(如企微管理员可编辑项)。
|
||||
依赖:models.base.Base。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy import DateTime, String, Text
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
class AppSetting(Base):
|
||||
"""
|
||||
应用运行时配置表(Key/Value)
|
||||
用途:将企业微信等管理员可编辑的配置长效保存到数据库,
|
||||
避免容器/部署重建后写入 backend/.env 的修改丢失。
|
||||
"""
|
||||
|
||||
__tablename__ = 'app_settings'
|
||||
|
||||
key: Mapped[str] = mapped_column(String(128), primary_key=True)
|
||||
value: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow,
|
||||
)
|
||||
@@ -0,0 +1,214 @@
|
||||
"""
|
||||
backend/app/models/shipping.py
|
||||
|
||||
用途:货代发货通知批次、任务、事件、库存文件与库存映射模型。
|
||||
依赖:models.base.Base。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import List, Optional
|
||||
|
||||
from sqlalchemy import Boolean, DateTime, Float, ForeignKey, Index, Integer, JSON, String, Text, UniqueConstraint, text
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
class ShippingBatch(Base):
|
||||
"""货代发货通知批次(一次多文件上传的聚合容器)"""
|
||||
|
||||
__tablename__ = 'shipping_batches'
|
||||
__table_args__ = (
|
||||
Index('ix_shipping_batches_user_created', 'user_id', 'created_at'),
|
||||
Index('ix_shipping_batches_conversation', 'conversation_id'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
batch_no: Mapped[str] = mapped_column(String(64), unique=True, index=True)
|
||||
user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), index=True, nullable=True)
|
||||
conversation_id: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
|
||||
current_focus_task_no: Mapped[Optional[str]] = mapped_column(
|
||||
String(64),
|
||||
ForeignKey(
|
||||
'shipping_tasks.task_no',
|
||||
name='fk_shipping_batches_current_focus_task_no_shipping_tasks',
|
||||
use_alter=True,
|
||||
),
|
||||
nullable=True,
|
||||
)
|
||||
file_count: Mapped[int] = mapped_column(Integer, default=1)
|
||||
process_summary_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
tasks: Mapped[List['ShippingTask']] = relationship(
|
||||
'ShippingTask',
|
||||
back_populates='batch',
|
||||
foreign_keys='ShippingTask.batch_id',
|
||||
)
|
||||
|
||||
|
||||
class ShippingTask(Base):
|
||||
"""货代发货通知 task(Chatflow Tool 编排状态机)"""
|
||||
|
||||
__tablename__ = 'shipping_tasks'
|
||||
__table_args__ = (
|
||||
Index('ix_shipping_tasks_user_status', 'user_id', 'process_status'),
|
||||
Index('ix_shipping_tasks_conversation', 'conversation_id'),
|
||||
Index('ix_shipping_tasks_batch_step', 'batch_id', 'current_step'),
|
||||
Index('ix_shipping_tasks_upload_status', 'upload_status'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
task_no: Mapped[str] = mapped_column(String(64), unique=True, index=True)
|
||||
batch_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_batches.id'), index=True, nullable=True)
|
||||
user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), index=True, nullable=True)
|
||||
conversation_id: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
|
||||
source_type: Mapped[str] = mapped_column(String(32), default='manual')
|
||||
source_file_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
source_file_type: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
batch_index: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
|
||||
batch_total: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
|
||||
|
||||
raw_content: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
customer_name: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
|
||||
customer_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
ship_to: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
po_number: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
required_date: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
lines_json: Mapped[Optional[list]] = mapped_column(JSON, default=list)
|
||||
parse_confidence: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
|
||||
|
||||
process_status: Mapped[str] = mapped_column(String(32), default='created', index=True)
|
||||
current_step: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
review_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
match_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
shortage_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
|
||||
line_results_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
||||
inventory_snapshot_id: Mapped[Optional[int]] = mapped_column(nullable=True)
|
||||
inventory_lines_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
||||
|
||||
export_file_path: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)
|
||||
export_file_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
export_version: Mapped[int] = mapped_column(Integer, default=1)
|
||||
freight_ref_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
upload_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
upload_mode: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
upload_attempt: Mapped[int] = mapped_column(Integer, default=0)
|
||||
idempotency_key: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
upload_started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
upload_finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
upload_error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
upload_error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
upload_receipt_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
|
||||
step_payload_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
|
||||
pending_human_reason: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
batch: Mapped[Optional['ShippingBatch']] = relationship(
|
||||
'ShippingBatch',
|
||||
back_populates='tasks',
|
||||
foreign_keys=[batch_id],
|
||||
)
|
||||
events: Mapped[List['ShippingTaskEvent']] = relationship(
|
||||
'ShippingTaskEvent',
|
||||
back_populates='task',
|
||||
cascade='all, delete-orphan',
|
||||
)
|
||||
|
||||
|
||||
class ShippingTaskEvent(Base):
|
||||
"""发货 task 审计事件"""
|
||||
|
||||
__tablename__ = 'shipping_task_events'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_tasks.id'), index=True)
|
||||
event_type: Mapped[str] = mapped_column(String(64), index=True)
|
||||
detail_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
|
||||
task: Mapped['ShippingTask'] = relationship('ShippingTask', back_populates='events')
|
||||
|
||||
|
||||
class ShippingInventoryFile(Base):
|
||||
"""货代发货批次库存快照文件,承载一次上传后可被多票任务共用的库存数据。"""
|
||||
|
||||
__tablename__ = 'shipping_inventory_files'
|
||||
__table_args__ = (
|
||||
Index('ix_shipping_inventory_files_batch_created', 'batch_id', 'created_at'),
|
||||
Index('ix_shipping_inventory_files_user_created', 'user_id', 'created_at'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
inventory_file_no: Mapped[str] = mapped_column(String(64), unique=True, index=True)
|
||||
batch_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_batches.id'), index=True, nullable=True)
|
||||
user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), index=True, nullable=True)
|
||||
source_file_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
storage_path: Mapped[str] = mapped_column(String(500), nullable=False)
|
||||
schema_preview_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
|
||||
field_mapping_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
|
||||
mapping_source: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
mapping_confirmed: Mapped[bool] = mapped_column(Boolean, default=False, server_default=text('false'))
|
||||
inventory_lines_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
||||
line_count: Mapped[int] = mapped_column(Integer, default=0)
|
||||
share_mode: Mapped[str] = mapped_column(String(32), default='task_only')
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
batch: Mapped[Optional['ShippingBatch']] = relationship('ShippingBatch', foreign_keys=[batch_id])
|
||||
links: Mapped[List['ShippingTaskInventoryLink']] = relationship(
|
||||
'ShippingTaskInventoryLink',
|
||||
back_populates='inventory_file',
|
||||
cascade='all, delete-orphan',
|
||||
)
|
||||
|
||||
|
||||
class ShippingTaskInventoryLink(Base):
|
||||
"""发货任务与库存快照的关联记录,一期每个任务只保留一条 active link。"""
|
||||
|
||||
__tablename__ = 'shipping_task_inventory_links'
|
||||
__table_args__ = (
|
||||
Index('ix_shipping_task_inventory_links_task_active', 'task_id', 'is_active'),
|
||||
Index('ix_shipping_task_inventory_links_file_active', 'inventory_file_id', 'is_active'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_tasks.id'), index=True)
|
||||
inventory_file_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_files.id'), index=True)
|
||||
link_role: Mapped[str] = mapped_column(String(32), default='member')
|
||||
access_mode: Mapped[str] = mapped_column(String(32), default='readonly')
|
||||
is_active: Mapped[bool] = mapped_column(Boolean, default=True, server_default=text('true'), index=True)
|
||||
linked_by_user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
linked_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
|
||||
task: Mapped['ShippingTask'] = relationship('ShippingTask', foreign_keys=[task_id])
|
||||
inventory_file: Mapped['ShippingInventoryFile'] = relationship(
|
||||
'ShippingInventoryFile',
|
||||
back_populates='links',
|
||||
foreign_keys=[inventory_file_id],
|
||||
)
|
||||
|
||||
|
||||
class ShippingInventoryMapping(Base):
|
||||
"""客户库存 Excel 表头 → 标准字段的列映射缓存(按 customer_code + header_hash 去重)。"""
|
||||
|
||||
__tablename__ = 'shipping_inventory_mappings'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('customer_code', 'header_hash', name='uq_shipping_inventory_mappings_customer_header'),
|
||||
Index('ix_shipping_inventory_mappings_customer_code', 'customer_code'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
customer_code: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
header_hash: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
headers_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
||||
field_mapping_json: Mapped[dict] = mapped_column(JSON, nullable=False, default=dict)
|
||||
last_used_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow, index=True)
|
||||
@@ -0,0 +1,48 @@
|
||||
"""
|
||||
backend/app/models/training.py
|
||||
|
||||
用途:定义新人入职培训记录模型,承载学员当前培训进度、成绩结算与 HR 统计来源。
|
||||
依赖:models.base.Base、SQLAlchemy 映射、users 主表外键。
|
||||
逻辑:每个用户维护一条当前培训记录;前端学习流与管理端统计都基于该表读写。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date, datetime
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy import Boolean, Date, DateTime, ForeignKey, Integer, JSON, String
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
class TrainingRecord(Base):
|
||||
"""新人入职培训当前记录。"""
|
||||
|
||||
__tablename__ = "training_records"
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), unique=True, index=True, nullable=False)
|
||||
employee_id: Mapped[Optional[str]] = mapped_column(String(50), nullable=True, index=True)
|
||||
name: Mapped[Optional[str]] = mapped_column(String(100), nullable=True, index=True)
|
||||
department: Mapped[Optional[str]] = mapped_column(String(100), nullable=True, index=True)
|
||||
join_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True, index=True)
|
||||
stage: Mapped[str] = mapped_column(String(20), nullable=False, default="video", index=True)
|
||||
current_question_index: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
|
||||
score: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
|
||||
passed: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False, index=True)
|
||||
attempt_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
|
||||
answer_details: Mapped[list[dict] | None] = mapped_column(JSON, nullable=True)
|
||||
started_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=datetime.utcnow)
|
||||
completion_time: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True, index=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=datetime.utcnow, index=True)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime,
|
||||
nullable=False,
|
||||
default=datetime.utcnow,
|
||||
onupdate=datetime.utcnow,
|
||||
index=True,
|
||||
)
|
||||
|
||||
user = relationship("User", back_populates="training_record")
|
||||
@@ -0,0 +1,116 @@
|
||||
"""
|
||||
backend/app/models/user.py
|
||||
|
||||
用途:用户账户、首页偏好、登录审计相关模型。
|
||||
依赖:models.base(Base、user_agent_permissions)。
|
||||
逻辑:User 与 Agent 多对多经 user_agent_permissions;admin/user API 主要读写本模块。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import List, Optional
|
||||
|
||||
from sqlalchemy import DateTime, ForeignKey, JSON, String
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
from werkzeug.security import check_password_hash, generate_password_hash
|
||||
|
||||
from app.models.base import Base, user_agent_permissions
|
||||
|
||||
|
||||
class UserHomepageConfig(Base):
|
||||
"""用户首页布局配置。"""
|
||||
|
||||
__tablename__ = 'user_homepage_configs'
|
||||
|
||||
user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), primary_key=True)
|
||||
layout: Mapped[dict] = mapped_column(JSON, default={})
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
|
||||
class UserFavoriteAgent(Base):
|
||||
"""用户收藏的 Agent。"""
|
||||
|
||||
__tablename__ = 'user_favorite_agents'
|
||||
|
||||
user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), primary_key=True)
|
||||
agent_id: Mapped[int] = mapped_column(ForeignKey('agents.id'), primary_key=True)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
|
||||
|
||||
class UserDefaultAgent(Base):
|
||||
"""用户嵌入首页的默认 Agent(最多 2 个)。"""
|
||||
|
||||
__tablename__ = 'user_default_agents'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
user_id: Mapped[int] = mapped_column(ForeignKey('users.id'))
|
||||
agent_id: Mapped[int] = mapped_column(ForeignKey('agents.id'))
|
||||
sort_order: Mapped[int] = mapped_column(default=0)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
|
||||
|
||||
class User(Base):
|
||||
"""系统用户:认证、RBAC、企微绑定、个人资料。"""
|
||||
|
||||
__tablename__ = 'users'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
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')
|
||||
status: Mapped[str] = mapped_column(String(20), default='active')
|
||||
password_hash: Mapped[Optional[str]] = mapped_column(String(255))
|
||||
language: Mapped[str] = mapped_column(String(10), default='zh-CN')
|
||||
theme_preference: Mapped[str] = mapped_column(String(10), default='system')
|
||||
wecom_userid: Mapped[Optional[str]] = mapped_column(String(128), unique=True, nullable=True)
|
||||
wecom_unionid: Mapped[Optional[str]] = mapped_column(String(128), unique=True, nullable=True)
|
||||
real_name: Mapped[Optional[str]] = mapped_column(String(50))
|
||||
employee_id: Mapped[Optional[str]] = mapped_column(String(50), unique=True)
|
||||
phone_number: Mapped[Optional[str]] = mapped_column(String(20), unique=True)
|
||||
default_agent_id: Mapped[Optional[int]] = mapped_column(ForeignKey('agents.id'))
|
||||
|
||||
agents: Mapped[List['Agent']] = relationship(
|
||||
secondary=user_agent_permissions,
|
||||
back_populates='users',
|
||||
)
|
||||
|
||||
reset_token: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
|
||||
reset_token_expiry: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
training_record: Mapped[Optional['TrainingRecord']] = relationship(
|
||||
'TrainingRecord',
|
||||
back_populates='user',
|
||||
uselist=False,
|
||||
)
|
||||
|
||||
def set_password(self, password: str) -> None:
|
||||
"""设置密码哈希。"""
|
||||
self.password_hash = generate_password_hash(password)
|
||||
|
||||
def check_password(self, password: str) -> bool:
|
||||
"""校验明文密码是否匹配。"""
|
||||
if not self.password_hash:
|
||||
return False
|
||||
return check_password_hash(self.password_hash, password)
|
||||
|
||||
|
||||
class LoginAudit(Base):
|
||||
"""登录审计:密码 / 企微登录结果。"""
|
||||
|
||||
__tablename__ = 'login_audits'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
username: Mapped[Optional[str]] = mapped_column(String(50), nullable=True)
|
||||
source: Mapped[str] = mapped_column(String(20), default='password')
|
||||
status: Mapped[str] = mapped_column(String(20), default='success')
|
||||
reason: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
match_rules: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
match_operator: Mapped[Optional[str]] = mapped_column(String(8), nullable=True)
|
||||
match_result: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
wecom_userid: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
ip: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
user_agent: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
@@ -0,0 +1,63 @@
|
||||
"""
|
||||
backend/app/models/wecom.py
|
||||
|
||||
用途:企业微信触达与回调审计模型。
|
||||
依赖:models.base.Base。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy import DateTime, ForeignKey, String, Text
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
class WecomNotifyAudit(Base):
|
||||
"""
|
||||
企业微信触达审计表
|
||||
用途:记录企微消息发送结果与回流点击数据
|
||||
"""
|
||||
|
||||
__tablename__ = 'wecom_notify_audits'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
event_type: Mapped[str] = mapped_column(String(64), index=True)
|
||||
status: Mapped[str] = mapped_column(String(20), default='sent', index=True)
|
||||
trace_id: Mapped[str] = mapped_column(String(64), unique=True, index=True)
|
||||
user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True, index=True)
|
||||
username: Mapped[Optional[str]] = mapped_column(String(50), nullable=True)
|
||||
wecom_userid: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
title: Mapped[Optional[str]] = mapped_column(String(120), nullable=True)
|
||||
content: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
jump_url: Mapped[Optional[str]] = mapped_column(String(512), nullable=True)
|
||||
error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
error_message: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
opened_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True, index=True)
|
||||
|
||||
|
||||
class WecomCallbackAudit(Base):
|
||||
"""
|
||||
企业微信回调审计表
|
||||
用途:记录消息与事件回调(安全模式解密后的内容摘要)
|
||||
"""
|
||||
|
||||
__tablename__ = 'wecom_callback_audits'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
msg_signature: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
timestamp: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
nonce: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
encrypt_raw: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
decrypted_xml: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
msg_type: Mapped[Optional[str]] = mapped_column(String(32), nullable=True, index=True)
|
||||
event: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
|
||||
from_user: Mapped[Optional[str]] = mapped_column(String(128), nullable=True, index=True)
|
||||
agent_id: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
msg_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
|
||||
error_message: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
@@ -1,62 +1,11 @@
|
||||
"""
|
||||
backend/app/response_utils.py
|
||||
用途:提供统一响应结构的工具函数(成功与失败)。
|
||||
说明:
|
||||
1. ok:构造 success=true 的响应体,数据统一放在 data 字段。
|
||||
2. error_payload:构造 success=false 的响应体,包含错误码、文案和可选详情。
|
||||
3. utc_iso_now:统一生成 UTC 时间戳,便于前后端与日志对齐。
|
||||
|
||||
用途:兼容层 — 权威实现位于 app.core.response。
|
||||
依赖:app.core.response。
|
||||
逻辑:create_app 全局 handler 使用 error_payload;新代码请 from app.core.response import ...。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
from app.core.response import error_payload, ok, utc_iso, utc_iso_now # noqa: F401
|
||||
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
from flask import jsonify
|
||||
|
||||
|
||||
def utc_iso_now() -> str:
|
||||
return datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
|
||||
|
||||
|
||||
def utc_iso(dt: datetime | None) -> str | None:
|
||||
"""将 naive UTC datetime 序列化为带 Z 后缀的 ISO 字符串,便于前端正确转本地时区。"""
|
||||
if dt is None:
|
||||
return None
|
||||
if dt.tzinfo is not None:
|
||||
return dt.astimezone(timezone.utc).replace(tzinfo=None).isoformat() + "Z"
|
||||
return dt.isoformat() + "Z"
|
||||
|
||||
|
||||
def ok(data: Any, *, request_id: str | None = None, status: int = 200):
|
||||
payload: dict[str, Any] = {
|
||||
"success": True,
|
||||
"data": data,
|
||||
"timestamp": utc_iso_now(),
|
||||
}
|
||||
if request_id:
|
||||
payload["request_id"] = request_id
|
||||
return jsonify(payload), status
|
||||
|
||||
|
||||
def error_payload(
|
||||
*,
|
||||
code: str,
|
||||
message: str,
|
||||
request_id: str | None = None,
|
||||
details: dict[str, Any] | None = None,
|
||||
retryable: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
payload: dict[str, Any] = {
|
||||
"success": False,
|
||||
"error": {
|
||||
"code": code,
|
||||
"message": message,
|
||||
"details": details or {},
|
||||
"retryable": retryable,
|
||||
},
|
||||
"timestamp": utc_iso_now(),
|
||||
}
|
||||
if request_id:
|
||||
payload["request_id"] = request_id
|
||||
return payload
|
||||
__all__ = ['error_payload', 'ok', 'utc_iso', 'utc_iso_now']
|
||||
@@ -0,0 +1,105 @@
|
||||
"""
|
||||
services/agent_category.py
|
||||
|
||||
用途:从 Agent.extra_config 解析 P1 分类字段(category / sub_category / sort_order),并提供排序与序列化。
|
||||
依赖:无外部服务;由 api/agents、api/user 在返回列表时调用。
|
||||
逻辑:分类信息暂存 extra_config,P2 可迁移至独立 agent_categories 表。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
|
||||
def parse_agent_category_meta(extra_config: dict | None) -> dict[str, Any]:
|
||||
"""
|
||||
从 extra_config 解析 Agent 分类元数据。
|
||||
核心逻辑:category / sub_category 去首尾空白;sort_order 非法值回退为 0。
|
||||
|
||||
Args:
|
||||
extra_config: Agent.extra_config JSON 字典,可为 None。
|
||||
|
||||
Returns:
|
||||
含 category (str)、sub_category (str)、sort_order (int) 的字典。
|
||||
"""
|
||||
extra = extra_config if isinstance(extra_config, dict) else {}
|
||||
category = str(extra.get('category') or '').strip()
|
||||
sub_category = str(extra.get('sub_category') or '').strip()
|
||||
sort_raw = extra.get('sort_order')
|
||||
try:
|
||||
sort_order = int(sort_raw) if sort_raw is not None and sort_raw != '' else 0
|
||||
except (TypeError, ValueError):
|
||||
sort_order = 0
|
||||
return {
|
||||
'category': category,
|
||||
'sub_category': sub_category,
|
||||
'sort_order': sort_order,
|
||||
}
|
||||
|
||||
|
||||
def _row_extra_config(row: Any) -> dict | None:
|
||||
"""从 ORM 行或 dict 行读取 extra_config。"""
|
||||
if hasattr(row, 'extra_config'):
|
||||
return row.extra_config
|
||||
if isinstance(row, dict):
|
||||
return row.get('extra_config')
|
||||
return None
|
||||
|
||||
|
||||
def _row_id(row: Any) -> int:
|
||||
"""从 ORM 行或 dict 行读取主键 id。"""
|
||||
if hasattr(row, 'id'):
|
||||
return int(row.id)
|
||||
if isinstance(row, dict):
|
||||
return int(row.get('id') or 0)
|
||||
return 0
|
||||
|
||||
|
||||
def agent_category_sort_key(row: Any) -> tuple:
|
||||
"""
|
||||
生成分类排序键:sort_order → category → sub_category → id。
|
||||
核心逻辑:未配置 category 的 Agent 排在同 sort_order 下的末尾(用 \\uffff 占位)。
|
||||
"""
|
||||
meta = parse_agent_category_meta(_row_extra_config(row))
|
||||
category_key = meta['category'] or '\uffff'
|
||||
sub_key = meta['sub_category'] or '\uffff'
|
||||
return (meta['sort_order'], category_key, sub_key, _row_id(row))
|
||||
|
||||
|
||||
def sort_agent_rows(rows: list) -> list:
|
||||
"""
|
||||
按分类元数据对 Agent 行列表原地排序并返回。
|
||||
"""
|
||||
return sorted(rows, key=agent_category_sort_key)
|
||||
|
||||
|
||||
def serialize_agent_category_fields(row: Any) -> dict[str, Any]:
|
||||
"""
|
||||
序列化分类相关 API 字段。
|
||||
空字符串 category / sub_category 输出为 None,便于前端区分「未配置」。
|
||||
"""
|
||||
meta = parse_agent_category_meta(_row_extra_config(row))
|
||||
return {
|
||||
'category': meta['category'] or None,
|
||||
'sub_category': meta['sub_category'] or None,
|
||||
'sort_order': meta['sort_order'],
|
||||
}
|
||||
|
||||
|
||||
def serialize_agent_list_item(row: Any) -> dict[str, Any]:
|
||||
"""
|
||||
序列化用户可见 Agent 列表项(聊天侧栏、工作台首页共用)。
|
||||
核心逻辑:合并基础字段、dify_app_type 与分类元数据。
|
||||
"""
|
||||
extra = _row_extra_config(row) or {}
|
||||
name = row.name if hasattr(row, 'name') else row.get('name')
|
||||
description = row.description if hasattr(row, 'description') else row.get('description')
|
||||
icon_url = row.icon_url if hasattr(row, 'icon_url') else row.get('icon_url')
|
||||
return {
|
||||
'id': _row_id(row),
|
||||
'name': name,
|
||||
'description': description,
|
||||
'icon_url': icon_url,
|
||||
'dify_app_type': extra.get('dify_app_type') or 'chatflow',
|
||||
**serialize_agent_category_fields(row),
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
"""
|
||||
backend/app/services/chat/hxops_context.py
|
||||
|
||||
用途:构建 HXOPS -> Dify 的平台统一上下文注入协议。
|
||||
依赖:无业务域依赖,仅提供平台级上下文结构与 refs 规范化工具。
|
||||
逻辑:由聊天入口、后台编排器或各 Agent 适配层调用本模块,统一生成 hxops_context,
|
||||
避免各业务目录重复定义 Dify Start 输入协议。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
HXOPS_CONTEXT_INPUT = "hxops_context"
|
||||
HXOPS_CONTEXT_SCHEMA_VERSION = "1"
|
||||
|
||||
|
||||
def build_ref(field: str, value: str | None) -> dict[str, str] | None:
|
||||
"""构建单个业务对象引用;缺值时返回 None。"""
|
||||
normalized_field = str(field or "").strip()
|
||||
normalized_value = str(value or "").strip()
|
||||
if not normalized_field or not normalized_value:
|
||||
return None
|
||||
return {"field": normalized_field, "value": normalized_value}
|
||||
|
||||
|
||||
def build_hxops_context(
|
||||
*,
|
||||
session_id: str,
|
||||
request_id: str | None = None,
|
||||
trigger_source: str | None = None,
|
||||
locale: str | None = None,
|
||||
refs: list[dict[str, str] | None] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
构建平台统一的 hxops_context。
|
||||
|
||||
设计约束:
|
||||
- 只注入平台基础信息与当前已知对象锚点
|
||||
- 不注入 query/files 等 Dify 原生输入
|
||||
- 不注入 checkpoint/stage 等运行态状态
|
||||
"""
|
||||
normalized_session_id = str(session_id or "").strip()
|
||||
if not normalized_session_id:
|
||||
return {}
|
||||
|
||||
request_payload: dict[str, str] = {}
|
||||
normalized_request_id = str(request_id or "").strip()
|
||||
normalized_trigger_source = str(trigger_source or "").strip()
|
||||
normalized_locale = str(locale or "").strip()
|
||||
if normalized_request_id:
|
||||
request_payload["id"] = normalized_request_id
|
||||
if normalized_trigger_source:
|
||||
request_payload["trigger_source"] = normalized_trigger_source
|
||||
if normalized_locale:
|
||||
request_payload["locale"] = normalized_locale
|
||||
|
||||
normalized_refs: list[dict[str, str]] = []
|
||||
seen_fields: set[str] = set()
|
||||
for item in refs or []:
|
||||
if not item:
|
||||
continue
|
||||
field = str(item.get("field") or "").strip()
|
||||
value = str(item.get("value") or "").strip()
|
||||
if not field or not value or field in seen_fields:
|
||||
continue
|
||||
normalized_refs.append({"field": field, "value": value})
|
||||
seen_fields.add(field)
|
||||
|
||||
return {
|
||||
"schema_version": HXOPS_CONTEXT_SCHEMA_VERSION,
|
||||
"session": {"id": normalized_session_id},
|
||||
"request": request_payload,
|
||||
"refs": normalized_refs,
|
||||
}
|
||||
|
||||
@@ -34,8 +34,9 @@ from typing import Any, List, Optional
|
||||
import requests
|
||||
from flask import current_app
|
||||
|
||||
from app.config import Config
|
||||
from app.models import ChatLog, db
|
||||
from app.core.config.settings import Config
|
||||
from app import db
|
||||
from app.models import ChatLog
|
||||
from app.services.chat_perf import ChatPerfTracker, chat_perf_enabled
|
||||
from app.services.integration_api import IntegrationApiService
|
||||
|
||||
@@ -512,6 +513,8 @@ class DifyService:
|
||||
hxops_turn_id: str | None = None,
|
||||
files: list[dict[str, Any]] | None = None,
|
||||
inputs: dict[str, Any] | None = None,
|
||||
persist_chat_log: bool = True,
|
||||
display_query: str | None = None,
|
||||
):
|
||||
"""
|
||||
主流程,调用 Dify、解析 SSE、记录日志、写库、向上游继续产出 SSE
|
||||
@@ -536,6 +539,7 @@ class DifyService:
|
||||
base_url = agent.api_base_url if agent.api_base_url else Config.DIFY_API_BASE
|
||||
url = DifyService._build_chat_messages_url(base_url)
|
||||
normalized_conversation_id = DifyService._normalize_dify_conversation_id(conversation_id)
|
||||
visible_query = str(display_query or query or '').strip()
|
||||
|
||||
headers = {
|
||||
'Authorization': f'Bearer {agent.dify_api_key}',
|
||||
@@ -592,6 +596,8 @@ class DifyService:
|
||||
return None
|
||||
|
||||
def persist_stream_chat(data: dict, event_name: str) -> None:
|
||||
if not persist_chat_log:
|
||||
return
|
||||
result = persist_stream_chat_async(data, event_name)
|
||||
if isinstance(result, dict):
|
||||
if result.get("chat_log_id") is not None:
|
||||
@@ -644,7 +650,7 @@ class DifyService:
|
||||
session_id=session_id,
|
||||
hxops_turn_id=hxops_turn_id,
|
||||
normalized_conversation_id=normalized_conversation_id,
|
||||
query=query,
|
||||
query=visible_query,
|
||||
answer_text=answer_snapshot,
|
||||
latency=latency_snapshot,
|
||||
retriever_resources=resources_snapshot,
|
||||
|
||||
@@ -12,7 +12,8 @@ from typing import Any, Optional
|
||||
|
||||
from flask import current_app
|
||||
|
||||
from app.models import ChatLog, QuickQuestion, db
|
||||
from app import db
|
||||
from app.models import ChatLog, QuickQuestion
|
||||
from app.services.faq_text_utils import normalize_faq_query
|
||||
|
||||
|
||||
|
||||
@@ -12,7 +12,8 @@ from typing import Any, Optional
|
||||
|
||||
from flask import current_app
|
||||
|
||||
from app.models import KbDifySyncRecord, QuickQuestion, db
|
||||
from app import db
|
||||
from app.models import KbDifySyncRecord, QuickQuestion
|
||||
from app.services.dify import DifyService
|
||||
from app.services.integration_api import IntegrationApiService
|
||||
|
||||
|
||||
@@ -1,93 +1,93 @@
|
||||
"""
|
||||
services/file_check_tools/dify_inputs.py
|
||||
|
||||
用途:构建文件检核 Chatflow 的 Dify chat inputs,并在 task_id 缺失时快速失败。
|
||||
依赖:task_resolver、agent_resolver、errors.ValidationError。
|
||||
逻辑:chat.py 在调 Dify 前调用本模块;缺失 schedule_task_id 时抛 ValidationError,避免 Dify 长连接挂死。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from app.errors import ValidationError
|
||||
from app.services.file_check_tools.task_resolver import resolve_schedule_task_id_from_agent
|
||||
|
||||
# Dify Chatflow「用户输入」变量名 — 须与画布 Start 节点配置一致
|
||||
FILE_CHECK_TASK_ID_INPUT = "task_id"
|
||||
FILE_CHECK_TASK_ID_MISSING_CODE = "file_check_task_id_required"
|
||||
|
||||
|
||||
def _missing_task_id_error(agent) -> ValidationError:
|
||||
"""
|
||||
构造 task_id 未配置时的业务异常。
|
||||
|
||||
核心逻辑:返回可操作的配置提示,供管理后台与前端直接展示。
|
||||
"""
|
||||
return ValidationError(
|
||||
"文件检核 Agent 未配置有效的 schedule_task_id,无法调用 Dify Chatflow。"
|
||||
"请在管理后台编辑该 Agent,于 extra_config 中设置 "
|
||||
"tool_run_progress.schedule_task_id(绑定排程任务 ID)。",
|
||||
details={
|
||||
"error_code": FILE_CHECK_TASK_ID_MISSING_CODE,
|
||||
"agent_id": getattr(agent, "id", None),
|
||||
"agent_name": getattr(agent, "name", None) or "",
|
||||
"config_hint": {
|
||||
"capabilities": ["tool_run_progress"],
|
||||
"tool_run_progress": {
|
||||
"type": "file_check",
|
||||
"schedule_task_id": "<ScheduleTask.id>",
|
||||
},
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def ensure_file_check_task_id_configured(agent) -> int:
|
||||
"""
|
||||
解析并校验文件检核 Agent 绑定的 schedule_task_id。
|
||||
|
||||
Args:
|
||||
agent: 当前对话 Agent。
|
||||
|
||||
Returns:
|
||||
有效的 ScheduleTask.id。
|
||||
|
||||
Raises:
|
||||
ValidationError: extra_config 未配置或 schedule_task_id 非法。
|
||||
"""
|
||||
task_id = resolve_schedule_task_id_from_agent(agent)
|
||||
if not task_id:
|
||||
raise _missing_task_id_error(agent)
|
||||
return task_id
|
||||
|
||||
|
||||
def build_file_check_dify_inputs(agent, *, required: bool = False) -> dict[str, str]:
|
||||
"""
|
||||
构建文件检核 Chatflow 的 Dify chat inputs。
|
||||
|
||||
仅注入 task_id。hxops_session_id / hxops_turn_id 由 chat.py 登记 turn 注册表,
|
||||
Tool API 启动时通过 user_message 推断,无需传入 Dify 画布。
|
||||
|
||||
Args:
|
||||
agent: 当前对话 Agent;task_id 从其 extra_config 解析。
|
||||
required: 为 True 时若 task_id 缺失立即抛 ValidationError,避免 Dify 流式挂死。
|
||||
|
||||
Returns:
|
||||
含 task_id 的 inputs 字典;required=False 且未配置时返回空 dict。
|
||||
|
||||
Raises:
|
||||
ValidationError: required=True 且 schedule_task_id 未配置。
|
||||
"""
|
||||
task_id = resolve_schedule_task_id_from_agent(agent)
|
||||
if not task_id:
|
||||
if required:
|
||||
raise _missing_task_id_error(agent)
|
||||
return {}
|
||||
return {FILE_CHECK_TASK_ID_INPUT: str(task_id)}
|
||||
|
||||
|
||||
__all__ = [
|
||||
"FILE_CHECK_TASK_ID_INPUT",
|
||||
"FILE_CHECK_TASK_ID_MISSING_CODE",
|
||||
"build_file_check_dify_inputs",
|
||||
"ensure_file_check_task_id_configured",
|
||||
]
|
||||
"""
|
||||
services/file_check_tools/dify_inputs.py
|
||||
|
||||
用途:构建文件检核 Chatflow 的 Dify chat inputs,并在 task_id 缺失时快速失败。
|
||||
依赖:task_resolver、agent_resolver、errors.ValidationError。
|
||||
逻辑:chat.py 在调 Dify 前调用本模块;缺失 schedule_task_id 时抛 ValidationError,避免 Dify 长连接挂死。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.file_check_tools.task_resolver import resolve_schedule_task_id_from_agent
|
||||
|
||||
# Dify Chatflow「用户输入」变量名 — 须与画布 Start 节点配置一致
|
||||
FILE_CHECK_TASK_ID_INPUT = "task_id"
|
||||
FILE_CHECK_TASK_ID_MISSING_CODE = "file_check_task_id_required"
|
||||
|
||||
|
||||
def _missing_task_id_error(agent) -> ValidationError:
|
||||
"""
|
||||
构造 task_id 未配置时的业务异常。
|
||||
|
||||
核心逻辑:返回可操作的配置提示,供管理后台与前端直接展示。
|
||||
"""
|
||||
return ValidationError(
|
||||
"文件检核 Agent 未配置有效的 schedule_task_id,无法调用 Dify Chatflow。"
|
||||
"请在管理后台编辑该 Agent,于 extra_config 中设置 "
|
||||
"tool_run_progress.schedule_task_id(绑定排程任务 ID)。",
|
||||
details={
|
||||
"error_code": FILE_CHECK_TASK_ID_MISSING_CODE,
|
||||
"agent_id": getattr(agent, "id", None),
|
||||
"agent_name": getattr(agent, "name", None) or "",
|
||||
"config_hint": {
|
||||
"capabilities": ["tool_run_progress"],
|
||||
"tool_run_progress": {
|
||||
"type": "file_check",
|
||||
"schedule_task_id": "<ScheduleTask.id>",
|
||||
},
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def ensure_file_check_task_id_configured(agent) -> int:
|
||||
"""
|
||||
解析并校验文件检核 Agent 绑定的 schedule_task_id。
|
||||
|
||||
Args:
|
||||
agent: 当前对话 Agent。
|
||||
|
||||
Returns:
|
||||
有效的 ScheduleTask.id。
|
||||
|
||||
Raises:
|
||||
ValidationError: extra_config 未配置或 schedule_task_id 非法。
|
||||
"""
|
||||
task_id = resolve_schedule_task_id_from_agent(agent)
|
||||
if not task_id:
|
||||
raise _missing_task_id_error(agent)
|
||||
return task_id
|
||||
|
||||
|
||||
def build_file_check_dify_inputs(agent, *, required: bool = False) -> dict[str, str]:
|
||||
"""
|
||||
构建文件检核 Chatflow 的 Dify chat inputs。
|
||||
|
||||
仅注入 task_id。hxops_session_id / hxops_turn_id 由 chat.py 登记 turn 注册表,
|
||||
Tool API 启动时通过 user_message 推断,无需传入 Dify 画布。
|
||||
|
||||
Args:
|
||||
agent: 当前对话 Agent;task_id 从其 extra_config 解析。
|
||||
required: 为 True 时若 task_id 缺失立即抛 ValidationError,避免 Dify 流式挂死。
|
||||
|
||||
Returns:
|
||||
含 task_id 的 inputs 字典;required=False 且未配置时返回空 dict。
|
||||
|
||||
Raises:
|
||||
ValidationError: required=True 且 schedule_task_id 未配置。
|
||||
"""
|
||||
task_id = resolve_schedule_task_id_from_agent(agent)
|
||||
if not task_id:
|
||||
if required:
|
||||
raise _missing_task_id_error(agent)
|
||||
return {}
|
||||
return {FILE_CHECK_TASK_ID_INPUT: str(task_id)}
|
||||
|
||||
|
||||
__all__ = [
|
||||
"FILE_CHECK_TASK_ID_INPUT",
|
||||
"FILE_CHECK_TASK_ID_MISSING_CODE",
|
||||
"build_file_check_dify_inputs",
|
||||
"ensure_file_check_task_id_configured",
|
||||
]
|
||||
|
||||
@@ -11,7 +11,7 @@ import re
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.errors import NotFoundError, ServiceUnavailableError, ValidationError
|
||||
from app.core.errors import NotFoundError, ServiceUnavailableError, ValidationError
|
||||
from app.models import KbGroup, ScheduleTask
|
||||
from app.services.knowledge_cleaning.dify_sync_service import KbDifySyncError, KbDifySyncService
|
||||
|
||||
|
||||
@@ -39,6 +39,7 @@ class FixedAssetsSnapshotService:
|
||||
"资产编号",
|
||||
"资产名称",
|
||||
"规格型号",
|
||||
"账套",
|
||||
"保管人姓名",
|
||||
"保管部门名称",
|
||||
"存放位置名称",
|
||||
@@ -74,6 +75,11 @@ class FixedAssetsSnapshotService:
|
||||
"X": "被资本",
|
||||
"Z": "停用",
|
||||
}
|
||||
ACCOUNT_BOOK_MAP = {
|
||||
"HXJM": "和信精密",
|
||||
"HTT": "和泰科技",
|
||||
"HTE": "和泰电子",
|
||||
}
|
||||
STOPWORDS_PATTERN = re.compile(
|
||||
r"(固定资产|固资|资产编号|财产编号|资产编码|编号|资产名称|设备名称|资产|设备|请问|帮我|看下|查下|查询|统计|核对|看看|我想知道|有多少台?|有多少|多少台?|多少|明细|列表|数据|结果|并且|以及|还有|和|按|根据|生成图表|生成excel|生成表单|导出excel|导出表单|导出)",
|
||||
re.IGNORECASE,
|
||||
@@ -132,6 +138,7 @@ class FixedAssetsSnapshotService:
|
||||
f"资产编号:{row.get('资产编号', '')}",
|
||||
f"资产名称:{row.get('资产名称', '')}",
|
||||
f"规格型号:{row.get('规格型号', '')}",
|
||||
f"账套:{row.get('账套', '')}({row.get('营运中心代码', '')})",
|
||||
f"保管人姓名:{row.get('保管人姓名', '')}",
|
||||
f"保管部门名称:{row.get('保管部门名称', '')}",
|
||||
f"存放位置名称:{row.get('存放位置名称', '')}",
|
||||
@@ -257,6 +264,10 @@ ORDER BY faj.faj02
|
||||
columns[idx]: cls._stringify(value)
|
||||
for idx, value in enumerate(raw_row)
|
||||
}
|
||||
item["账套"] = cls.ACCOUNT_BOOK_MAP.get(
|
||||
item.get("营运中心代码", "").strip().upper(),
|
||||
item.get("营运中心代码", ""),
|
||||
)
|
||||
item["资产状态"] = cls.STATUS_MAP.get(item.get("资产状态代码", "").upper(), item.get("资产状态代码", ""))
|
||||
item["资产性质"] = cls.NATURE_MAP.get(item.get("资产性质代码", ""), item.get("资产性质代码", ""))
|
||||
item["备注"] = cls._build_remark(item)
|
||||
@@ -391,6 +402,7 @@ INSERT INTO fixed_assets (
|
||||
item.get("资产编号", ""),
|
||||
item.get("资产名称", ""),
|
||||
item.get("规格型号", ""),
|
||||
item.get("账套", ""),
|
||||
item.get("保管人姓名", ""),
|
||||
item.get("保管部门名称", ""),
|
||||
item.get("存放位置名称", ""),
|
||||
@@ -460,23 +472,29 @@ INSERT INTO fixed_assets (
|
||||
cls._log("warning", f"Failed to remove temp snapshot file {temp_file}: {exc}")
|
||||
|
||||
@classmethod
|
||||
def _cleanup_history_snapshots(cls, keep_count: int | None = None) -> None:
|
||||
"""仅保留最新 N 份历史快照,额外旧文件自动清理。"""
|
||||
cls._ensure_storage_dirs()
|
||||
snapshots_dir = cls._snapshots_dir()
|
||||
cls._cleanup_temp_snapshot_files(snapshots_dir)
|
||||
def _cleanup_versioned_files(
|
||||
cls,
|
||||
directory: Path,
|
||||
*,
|
||||
patterns: tuple[str, ...],
|
||||
keep_count: int,
|
||||
) -> None:
|
||||
"""按版本号仅保留最近 N 份历史文件,跳过 latest 固定别名文件。"""
|
||||
if not directory.exists():
|
||||
return
|
||||
|
||||
safe_keep_count = max(1, int(keep_count or current_app.config.get("FIXED_ASSETS_HISTORY_KEEP_COUNT", 3) or 3))
|
||||
version_files: dict[str, list[Path]] = {}
|
||||
for pattern in ("FixedAssets_*.db", "FixedAssets_*.xlsx"):
|
||||
for file_path in snapshots_dir.glob(pattern):
|
||||
for pattern in patterns:
|
||||
for file_path in directory.glob(pattern):
|
||||
if file_path.name.startswith("~$"):
|
||||
continue
|
||||
version_key = file_path.stem
|
||||
version_files.setdefault(version_key, []).append(file_path)
|
||||
match = re.fullmatch(r"FixedAssets_(\d{8}_\d{6})", file_path.stem)
|
||||
if not match:
|
||||
continue
|
||||
version_files.setdefault(match.group(1), []).append(file_path)
|
||||
|
||||
version_keys = sorted(version_files.keys(), reverse=True)
|
||||
obsolete_keys = version_keys[safe_keep_count:]
|
||||
obsolete_keys = version_keys[keep_count:]
|
||||
for version_key in obsolete_keys:
|
||||
for file_path in version_files.get(version_key, []):
|
||||
try:
|
||||
@@ -484,6 +502,28 @@ INSERT INTO fixed_assets (
|
||||
except OSError as exc:
|
||||
cls._log("warning", f"Failed to remove obsolete snapshot file {file_path}: {exc}")
|
||||
|
||||
@classmethod
|
||||
def _cleanup_history_snapshots(cls, keep_count: int | None = None) -> None:
|
||||
"""仅保留最新 N 份历史快照,额外旧文件自动清理。"""
|
||||
cls._ensure_storage_dirs()
|
||||
snapshots_dir = cls._snapshots_dir()
|
||||
cls._cleanup_temp_snapshot_files(snapshots_dir)
|
||||
safe_keep_count = max(1, int(keep_count or current_app.config.get("FIXED_ASSETS_HISTORY_KEEP_COUNT", 3) or 3))
|
||||
cls._cleanup_versioned_files(
|
||||
snapshots_dir,
|
||||
patterns=("FixedAssets_*.db", "FixedAssets_*.xlsx"),
|
||||
keep_count=safe_keep_count,
|
||||
)
|
||||
|
||||
if current_app.config.get("FIXED_ASSETS_EXPORT_TO_DOCS", True):
|
||||
docs_root = cls._docs_export_root()
|
||||
cls._cleanup_temp_snapshot_files(docs_root)
|
||||
cls._cleanup_versioned_files(
|
||||
docs_root,
|
||||
patterns=("FixedAssets_*.xlsx",),
|
||||
keep_count=safe_keep_count,
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def is_snapshot_available(cls) -> bool:
|
||||
return cls._latest_db_path().exists()
|
||||
@@ -728,6 +768,7 @@ WITH deduped_assets AS (
|
||||
asset_no AS "资产编号",
|
||||
asset_name AS "资产名称",
|
||||
specification AS "规格型号",
|
||||
operating_center_code AS "账套",
|
||||
custodian_name AS "保管人姓名",
|
||||
department_name AS "保管部门名称",
|
||||
location_name AS "存放位置名称",
|
||||
|
||||
@@ -40,7 +40,8 @@ from typing import Any, Optional
|
||||
from flask import current_app
|
||||
from sqlalchemy.orm import joinedload
|
||||
|
||||
from app.models import Agent, ChatLog, QuickQuestion, db
|
||||
from app import db
|
||||
from app.models import Agent, ChatLog, QuickQuestion
|
||||
from app.services.faq_hot_settings import read_faq_hot_env
|
||||
from app.services.faq_text_utils import normalize_faq_query
|
||||
from app.services.hot_faq_candidate_store import HotFaqCandidateStore
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
backend/app/services/hot_faq_candidate_store.py
|
||||
|
||||
用途:热点 FAQ 候选池 PostgreSQL 读写(离线聚合结果,不含在线命中)。
|
||||
依赖:models.FaqHotCandidate、Agent、faq_hot_settings、SQLAlchemy db。
|
||||
依赖:models.FaqHotCandidate、Agent、faq_hot_settings、app.extensions.db。
|
||||
逻辑:HotFaqAggregator 写入;管理端 API 读取 / 晋升 / 忽略。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
@@ -13,7 +13,8 @@ from typing import Any, Optional
|
||||
from flask import current_app
|
||||
from sqlalchemy import desc, or_
|
||||
|
||||
from app.models import Agent, FaqHotCandidate, db
|
||||
from app import db
|
||||
from app.models import Agent, FaqHotCandidate
|
||||
from app.services.faq_hot_settings import read_faq_hot_env
|
||||
|
||||
|
||||
|
||||
@@ -445,7 +445,8 @@ WHERE c002001 = ?
|
||||
latency,
|
||||
)
|
||||
|
||||
from app.models import ChatLog, db
|
||||
from app import db
|
||||
from app.models import ChatLog
|
||||
|
||||
chat_log_id = None
|
||||
try:
|
||||
|
||||
@@ -8,7 +8,7 @@ from urllib.parse import urlparse
|
||||
import requests
|
||||
from flask import current_app, has_app_context, has_request_context, request
|
||||
|
||||
from app.config import Config
|
||||
from app.core.config.settings import Config
|
||||
|
||||
|
||||
class IntegrationApiService:
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
"""
|
||||
backend/app/services/kb/__init__.py
|
||||
|
||||
用途:知识库域服务包(收敛 knowledge_cleaning/)。
|
||||
逻辑:Wave 2–4 逐步 alias 至 knowledge_cleaning 子模块。
|
||||
用途:知识库域服务包(收敛 knowledge_cleaning/ 与 KB API 业务编排)。
|
||||
逻辑:按需 import 子模块 document_service、markdown、path_upload_service、storage、job_lifecycle。
|
||||
"""
|
||||
from app.services import knowledge_cleaning # noqa: F401
|
||||
from app.services import knowledge_cleaning
|
||||
from app.services.kb import document_service, job_lifecycle, markdown, path_upload_service, storage
|
||||
|
||||
__all__ = ['knowledge_cleaning']
|
||||
__all__ = ['document_service', 'job_lifecycle', 'knowledge_cleaning', 'markdown', 'path_upload_service', 'storage']
|
||||
@@ -0,0 +1,429 @@
|
||||
"""
|
||||
backend/app/services/kb/document_service.py
|
||||
|
||||
用途:知识库文档版本、Markdown、上传/清洗/同步/删除业务编排。
|
||||
依赖:models、services/kb/storage、services/kb/job_lifecycle、app.jobs、knowledge_cleaning。
|
||||
逻辑:由 api/kb/documents.py 调用;path_upload 软删委托本模块 soft_delete_document。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from werkzeug.datastructures import FileStorage
|
||||
from sqlalchemy.orm import joinedload
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.jobs import enqueue_clean_job, enqueue_kb_job
|
||||
from app.models import KbDifySyncRecord, KbDocument, KbDocumentVersion, KbJob
|
||||
from app.services.kb.job_lifecycle import (
|
||||
cancel_active_kb_jobs_for_documents,
|
||||
latest_job_for_version,
|
||||
serialize_job,
|
||||
)
|
||||
from app.services.kb.markdown import (
|
||||
markdown_unavailable_message,
|
||||
resolve_markdown_read_path,
|
||||
resolve_markdown_write_path,
|
||||
serialize_markdown_payload,
|
||||
)
|
||||
from app.services.kb.storage import kb_storage_root, resolve_storage_path, safe_upload_filename, save_upload
|
||||
from app.services.knowledge_cleaning.dify_sync_service import delete_document_from_dify
|
||||
|
||||
|
||||
def _serialize_version(version: KbDocumentVersion | None) -> dict | None:
|
||||
"""内联版本序列化,避免 api 层 import。"""
|
||||
if version is None:
|
||||
return None
|
||||
return {
|
||||
'id': version.id,
|
||||
'document_id': version.document_id,
|
||||
'version_no': version.version_no,
|
||||
'status': version.status,
|
||||
'is_current': version.is_current,
|
||||
'source_file_name': version.source_file_name,
|
||||
'source_file_ext': version.source_file_ext,
|
||||
'source_file_size': version.source_file_size,
|
||||
'sha256': version.sha256,
|
||||
'cleaned_file_path': version.cleaned_file_path,
|
||||
'cleaned_preview_path': version.cleaned_preview_path,
|
||||
'error_message': version.error_message,
|
||||
'created_at': version.created_at.isoformat() if version.created_at else None,
|
||||
}
|
||||
|
||||
|
||||
def _current_version(document: KbDocument) -> KbDocumentVersion | None:
|
||||
versions = list(getattr(document, 'versions', []) or [])
|
||||
if not versions:
|
||||
return None
|
||||
return next((item for item in versions if item.is_current), versions[0])
|
||||
|
||||
|
||||
def _next_version_no(document: KbDocument) -> int:
|
||||
versions = list(getattr(document, 'versions', []) or [])
|
||||
if not versions:
|
||||
return 1
|
||||
return max(item.version_no for item in versions) + 1
|
||||
|
||||
|
||||
def load_document(document_id: int, *, with_versions: bool = False) -> KbDocument:
|
||||
"""
|
||||
加载未删除文档;不存在则 NotFoundError。
|
||||
Args:
|
||||
document_id: KbDocument 主键。
|
||||
with_versions: 是否 eager load versions。
|
||||
"""
|
||||
query = db.session.query(KbDocument)
|
||||
if with_versions:
|
||||
query = query.options(joinedload(KbDocument.versions))
|
||||
document = query.filter(KbDocument.id == document_id, KbDocument.is_deleted.is_(False)).first()
|
||||
if not document:
|
||||
raise NotFoundError('Knowledge base document not found')
|
||||
return document
|
||||
|
||||
|
||||
def load_document_version(version_id: int) -> KbDocumentVersion:
|
||||
"""加载文档版本及其 document;无效则 NotFoundError。"""
|
||||
version = (
|
||||
db.session.query(KbDocumentVersion)
|
||||
.options(joinedload(KbDocumentVersion.document))
|
||||
.filter(KbDocumentVersion.id == version_id)
|
||||
.first()
|
||||
)
|
||||
if not version or not version.document or version.document.is_deleted:
|
||||
raise NotFoundError('知识库文档版本不存在')
|
||||
return version
|
||||
|
||||
|
||||
def list_document_versions(document_id: int) -> list[KbDocumentVersion]:
|
||||
"""返回文档全部版本(已校验文档存在)。"""
|
||||
document = load_document(document_id, with_versions=True)
|
||||
return list(document.versions)
|
||||
|
||||
|
||||
def resolve_source_file_path(version_id: int) -> tuple[Path, str]:
|
||||
"""
|
||||
解析版本原始文件路径。
|
||||
Returns:
|
||||
(绝对路径, 下载文件名)。
|
||||
"""
|
||||
version = load_document_version(version_id)
|
||||
source_path = resolve_storage_path(version.source_file_path)
|
||||
if not source_path or not source_path.exists():
|
||||
raise NotFoundError('原始文件不存在或已被移除')
|
||||
filename = version.source_file_name or source_path.name
|
||||
return source_path, filename
|
||||
|
||||
|
||||
def list_sync_records(document_id: int) -> list[KbDifySyncRecord]:
|
||||
"""返回文档 Dify 同步记录列表。"""
|
||||
load_document(document_id)
|
||||
return (
|
||||
db.session.query(KbDifySyncRecord)
|
||||
.filter(KbDifySyncRecord.document_id == document_id)
|
||||
.order_by(KbDifySyncRecord.updated_at.desc(), KbDifySyncRecord.id.desc())
|
||||
.all()
|
||||
)
|
||||
|
||||
|
||||
def read_markdown(document_id: int) -> dict:
|
||||
"""
|
||||
读取文档 Markdown 内容与类型。
|
||||
Returns:
|
||||
serialize_markdown_payload 格式的 dict。
|
||||
"""
|
||||
document = load_document(document_id, with_versions=True)
|
||||
version = _current_version(document)
|
||||
if not version:
|
||||
raise NotFoundError('当前文档暂无版本记录')
|
||||
markdown_path, kind = resolve_markdown_read_path(version)
|
||||
if not markdown_path:
|
||||
raise ConflictError(markdown_unavailable_message(version))
|
||||
content = markdown_path.read_text(encoding='utf-8', errors='ignore')
|
||||
return serialize_markdown_payload(document, version, content, kind)
|
||||
|
||||
|
||||
def update_markdown(document_id: int, content: str, *, user_id: int | None) -> dict:
|
||||
"""写入 Markdown 并更新版本/文档状态。"""
|
||||
if not isinstance(content, str):
|
||||
raise ValidationError('content is required')
|
||||
document = load_document(document_id, with_versions=True)
|
||||
version = _current_version(document)
|
||||
if not version:
|
||||
raise NotFoundError('当前文档暂无版本记录')
|
||||
markdown_path = resolve_markdown_write_path(version)
|
||||
if not markdown_path:
|
||||
raise ConflictError(markdown_unavailable_message(version))
|
||||
markdown_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
markdown_path.write_text(content, encoding='utf-8')
|
||||
version.cleaned_file_path = str(markdown_path)
|
||||
version.cleaned_preview_path = str(markdown_path)
|
||||
version.word_count = len(content.split())
|
||||
version.status = 'cleaned'
|
||||
version.converted_at = datetime.utcnow()
|
||||
version.error_message = None
|
||||
document.status = 'ready'
|
||||
document.updated_by_id = user_id
|
||||
return serialize_markdown_payload(document, version, content, 'markdown')
|
||||
|
||||
|
||||
def upload_new_version(
|
||||
document_id: int,
|
||||
file_storage: FileStorage,
|
||||
*,
|
||||
user_id: int | None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
上传新版本文件并创建 clean KbJob。
|
||||
Returns:
|
||||
API 响应 dict(accepted、version、clean_job、queue_result)。
|
||||
"""
|
||||
document = load_document(document_id, with_versions=True)
|
||||
if not file_storage or not file_storage.filename:
|
||||
raise ValidationError('file is required')
|
||||
|
||||
filename = safe_upload_filename(file_storage.filename)
|
||||
version_no = _next_version_no(document)
|
||||
ext = Path(filename).suffix.lower().lstrip('.') or None
|
||||
version_dir = (
|
||||
kb_storage_root()
|
||||
/ f'group_{document.group_id:04d}'
|
||||
/ f'document_{document.id:06d}'
|
||||
/ f'v{version_no:03d}'
|
||||
)
|
||||
target_path = version_dir / filename
|
||||
sha256, file_size = save_upload(file_storage, target_path)
|
||||
|
||||
for old in document.versions:
|
||||
if old.is_current:
|
||||
old.is_current = False
|
||||
|
||||
version = KbDocumentVersion(
|
||||
document_id=document.id,
|
||||
version_no=version_no,
|
||||
status='uploaded',
|
||||
is_current=True,
|
||||
source_file_name=filename,
|
||||
source_file_path=str(target_path),
|
||||
source_file_ext=ext,
|
||||
source_file_size=file_size,
|
||||
sha256=sha256,
|
||||
uploaded_by_id=user_id,
|
||||
)
|
||||
db.session.add(version)
|
||||
db.session.flush()
|
||||
|
||||
document.source_type = 'upload'
|
||||
document.updated_by_id = user_id
|
||||
|
||||
upload_job = KbJob(
|
||||
job_type='upload',
|
||||
status='success',
|
||||
group_id=document.group_id,
|
||||
document_id=document.id,
|
||||
document_version_id=version.id,
|
||||
progress=100,
|
||||
message=f'已上传原始文件:{filename}',
|
||||
payload_json={'source_file_name': filename, 'source_file_size': file_size},
|
||||
result_json={'sha256': sha256, 'stored_path': str(target_path)},
|
||||
created_by_id=user_id,
|
||||
started_at=version.created_at,
|
||||
finished_at=version.created_at,
|
||||
)
|
||||
clean_job = KbJob(
|
||||
job_type='clean',
|
||||
status='queued',
|
||||
group_id=document.group_id,
|
||||
document_id=document.id,
|
||||
document_version_id=version.id,
|
||||
progress=0,
|
||||
message='等待接入清洗任务链路',
|
||||
payload_json={'document_version_id': version.id, 'source_file_name': filename},
|
||||
created_by_id=user_id,
|
||||
)
|
||||
db.session.add(upload_job)
|
||||
db.session.add(clean_job)
|
||||
db.session.commit()
|
||||
|
||||
_enqueued, queue_result = enqueue_clean_job(clean_job.id)
|
||||
db.session.expire_all()
|
||||
version = db.session.get(KbDocumentVersion, version.id)
|
||||
clean_job = db.session.get(KbJob, clean_job.id)
|
||||
|
||||
return {
|
||||
'accepted': True,
|
||||
'message': '文件上传成功,清洗已排队',
|
||||
'queue_result': queue_result,
|
||||
'version': _serialize_version(version),
|
||||
'clean_job': serialize_job(clean_job) if clean_job else None,
|
||||
}
|
||||
|
||||
|
||||
def submit_clean(document_id: int, *, user_id: int | None) -> tuple[dict[str, Any], int]:
|
||||
"""
|
||||
提交或触发文档清洗任务。
|
||||
Returns:
|
||||
(响应 payload, HTTP status_code)。
|
||||
"""
|
||||
document = load_document(document_id, with_versions=True)
|
||||
version = _current_version(document)
|
||||
if not version:
|
||||
raise ValidationError('当前文档暂无可清洗版本')
|
||||
|
||||
latest_clean_job = latest_job_for_version(version.id, 'clean')
|
||||
if latest_clean_job and latest_clean_job.status == 'running':
|
||||
payload = serialize_job(latest_clean_job)
|
||||
payload['accepted'] = True
|
||||
payload['queue_result'] = 'already_running'
|
||||
payload['message'] = latest_clean_job.message or '清洗任务正在执行中'
|
||||
return payload, 202
|
||||
|
||||
if latest_clean_job and latest_clean_job.status == 'queued':
|
||||
from app.services.knowledge_cleaning.tasks import run_clean_job
|
||||
|
||||
_ok, _message = run_clean_job(latest_clean_job.id)
|
||||
db.session.expire_all()
|
||||
refreshed = db.session.get(KbJob, latest_clean_job.id)
|
||||
payload = serialize_job(refreshed) if refreshed else {'id': latest_clean_job.id}
|
||||
payload['accepted'] = True
|
||||
payload['queue_result'] = 'inline_on_manual'
|
||||
payload['message'] = (refreshed.message if refreshed else None) or _message or '清洗任务已执行'
|
||||
status_code = 200 if refreshed and refreshed.status == 'success' else 202
|
||||
return payload, status_code
|
||||
|
||||
version.status = 'uploaded'
|
||||
version.error_message = None
|
||||
if document.status == 'failed':
|
||||
document.status = 'uploaded'
|
||||
document.updated_by_id = user_id
|
||||
|
||||
clean_job = KbJob(
|
||||
job_type='clean',
|
||||
status='queued',
|
||||
group_id=document.group_id,
|
||||
document_id=document.id,
|
||||
document_version_id=version.id,
|
||||
progress=0,
|
||||
message='等待清洗任务执行',
|
||||
payload_json={
|
||||
'document_version_id': version.id,
|
||||
'document_id': document.id,
|
||||
'source_file_name': version.source_file_name,
|
||||
'retry_mode': 'manual',
|
||||
},
|
||||
created_by_id=user_id,
|
||||
)
|
||||
db.session.add(clean_job)
|
||||
db.session.commit()
|
||||
|
||||
_enqueued, queue_result = enqueue_clean_job(clean_job.id)
|
||||
refreshed = db.session.get(KbJob, clean_job.id)
|
||||
payload = serialize_job(refreshed) if refreshed else {'id': clean_job.id}
|
||||
payload['accepted'] = True
|
||||
payload['queue_result'] = queue_result
|
||||
payload['message'] = refreshed.message if refreshed else '清洗任务已提交,等待后台处理'
|
||||
return payload, 202
|
||||
|
||||
|
||||
def submit_sync(document_id: int, *, user_id: int | None) -> dict[str, Any]:
|
||||
"""创建 sync_dify KbJob 并入队。"""
|
||||
document = load_document(document_id, with_versions=True)
|
||||
version = _current_version(document)
|
||||
if not version:
|
||||
raise ValidationError('当前文档没有可同步的版本')
|
||||
|
||||
sync_job = KbJob(
|
||||
job_type='sync_dify',
|
||||
status='queued',
|
||||
group_id=document.group_id,
|
||||
document_id=document.id,
|
||||
document_version_id=version.id,
|
||||
progress=0,
|
||||
message='等待同步到 Dify',
|
||||
payload_json={'document_version_id': version.id, 'document_id': document.id},
|
||||
created_by_id=user_id,
|
||||
)
|
||||
db.session.add(sync_job)
|
||||
db.session.commit()
|
||||
|
||||
_enqueued, queue_result = enqueue_kb_job(sync_job.id)
|
||||
refreshed = db.session.get(KbJob, sync_job.id)
|
||||
payload = serialize_job(refreshed) if refreshed else {'id': sync_job.id}
|
||||
payload['accepted'] = True
|
||||
payload['queue_result'] = queue_result
|
||||
payload['message'] = refreshed.message if refreshed else '同步任务已提交,等待后台处理'
|
||||
return payload
|
||||
|
||||
|
||||
def update_metadata(document_id: int, data: dict, *, user_id: int | None) -> KbDocument:
|
||||
"""更新文档 title/description/status。"""
|
||||
document = load_document(document_id)
|
||||
title = str(data.get('title') or document.title).strip()
|
||||
description = data.get('description')
|
||||
status = str(data.get('status') or document.status).strip()
|
||||
if not title:
|
||||
raise ValidationError('title is required')
|
||||
duplicate = (
|
||||
db.session.query(KbDocument)
|
||||
.filter(
|
||||
KbDocument.id != document.id,
|
||||
KbDocument.group_id == document.group_id,
|
||||
KbDocument.title == title,
|
||||
KbDocument.is_deleted.is_(False),
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if duplicate:
|
||||
raise ValidationError('当前分组下已存在同名文档')
|
||||
document.title = title
|
||||
document.description = str(description).strip() or None if description is not None else None
|
||||
document.status = status or document.status
|
||||
document.updated_by_id = user_id
|
||||
return document
|
||||
|
||||
|
||||
def soft_delete_document(document_id: int | None, user_id: int | None) -> bool:
|
||||
"""
|
||||
软删文档、尝试删 Dify 远端并取消关联后台任务。
|
||||
Returns:
|
||||
是否成功标记删除。
|
||||
"""
|
||||
if not document_id:
|
||||
return False
|
||||
document = db.session.get(KbDocument, document_id)
|
||||
if not document or document.is_deleted:
|
||||
return False
|
||||
try:
|
||||
delete_document_from_dify(document.id)
|
||||
except Exception:
|
||||
pass
|
||||
document.is_deleted = True
|
||||
document.updated_by_id = user_id
|
||||
cancel_active_kb_jobs_for_documents([document.id], '文档已删除,后台任务已取消')
|
||||
return True
|
||||
|
||||
|
||||
def delete_document(document_id: int, *, user_id: int | None) -> dict[str, Any]:
|
||||
"""软删文档并返回 API 结果。"""
|
||||
document = db.session.get(KbDocument, document_id)
|
||||
if not document or document.is_deleted:
|
||||
raise NotFoundError('Knowledge base document not found')
|
||||
|
||||
delete_result = None
|
||||
try:
|
||||
delete_result = delete_document_from_dify(document.id)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
document.is_deleted = True
|
||||
document.updated_by_id = user_id
|
||||
cancelled_jobs = cancel_active_kb_jobs_for_documents([document.id], '文档已删除,后台任务已取消')
|
||||
db.session.commit()
|
||||
return {
|
||||
'ok': True,
|
||||
'id': document_id,
|
||||
'delete_dify': delete_result,
|
||||
'cancelled_jobs': cancelled_jobs,
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
"""
|
||||
backend/app/services/kb/job_lifecycle.py
|
||||
|
||||
用途:KbJob 序列化与取消(文档/分组删除时)。
|
||||
依赖:models.KbJob、KbDocumentVersion。
|
||||
逻辑:api/kb/jobs 薄 re-export;services 层直接引用本模块。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from app import db
|
||||
from app.models import KbDocumentVersion, KbJob
|
||||
|
||||
|
||||
def serialize_job(job: KbJob) -> dict:
|
||||
"""将 KbJob ORM 转为 API JSON 形状。"""
|
||||
return {
|
||||
'id': job.id,
|
||||
'job_type': job.job_type,
|
||||
'status': job.status,
|
||||
'group_id': job.group_id,
|
||||
'document_id': job.document_id,
|
||||
'document_version_id': job.document_version_id,
|
||||
'progress': job.progress,
|
||||
'message': job.message,
|
||||
'error_message': job.error_message,
|
||||
'payload_json': job.payload_json,
|
||||
'result_json': job.result_json,
|
||||
'created_at': job.created_at.isoformat() if job.created_at else None,
|
||||
'started_at': job.started_at.isoformat() if job.started_at else None,
|
||||
'finished_at': job.finished_at.isoformat() if job.finished_at else None,
|
||||
}
|
||||
|
||||
|
||||
def latest_job_for_version(version_id: int, job_type: str) -> KbJob | None:
|
||||
"""查询某文档版本最近一条指定类型的 KbJob。"""
|
||||
return (
|
||||
db.session.query(KbJob)
|
||||
.filter(
|
||||
KbJob.document_version_id == version_id,
|
||||
KbJob.job_type == job_type,
|
||||
)
|
||||
.order_by(KbJob.created_at.desc(), KbJob.id.desc())
|
||||
.first()
|
||||
)
|
||||
|
||||
|
||||
def cancel_active_kb_jobs_for_documents(document_ids: list[int], message: str) -> int:
|
||||
"""取消已删除文档关联的 clean/sync_dify 后台任务。"""
|
||||
ids = [int(item) for item in document_ids if item]
|
||||
if not ids:
|
||||
return 0
|
||||
|
||||
version_ids = [
|
||||
row[0]
|
||||
for row in db.session.query(KbDocumentVersion.id)
|
||||
.filter(KbDocumentVersion.document_id.in_(ids))
|
||||
.all()
|
||||
]
|
||||
query = db.session.query(KbJob).filter(
|
||||
KbJob.status.in_(('queued', 'running')),
|
||||
KbJob.job_type.in_(('clean', 'sync_dify')),
|
||||
)
|
||||
if version_ids:
|
||||
query = query.filter(
|
||||
(KbJob.document_id.in_(ids)) | (KbJob.document_version_id.in_(version_ids))
|
||||
)
|
||||
else:
|
||||
query = query.filter(KbJob.document_id.in_(ids))
|
||||
|
||||
now = datetime.utcnow()
|
||||
cancelled = 0
|
||||
for job in query.all():
|
||||
job.status = 'cancelled'
|
||||
job.progress = 100
|
||||
job.message = message
|
||||
job.error_message = None
|
||||
job.finished_at = job.finished_at or now
|
||||
cancelled += 1
|
||||
return cancelled
|
||||
|
||||
|
||||
def cancel_active_kb_jobs_for_group(group_id: int, message: str) -> int:
|
||||
"""取消已停用知识库分组下仍未完成的后台任务。"""
|
||||
now = datetime.utcnow()
|
||||
jobs = (
|
||||
db.session.query(KbJob)
|
||||
.filter(
|
||||
KbJob.group_id == group_id,
|
||||
KbJob.status.in_(('draft', 'staging', 'queued', 'running')),
|
||||
KbJob.job_type.in_(('path_upload', 'clean', 'sync_dify')),
|
||||
)
|
||||
.all()
|
||||
)
|
||||
for job in jobs:
|
||||
job.status = 'cancelled'
|
||||
job.progress = 100
|
||||
job.message = message
|
||||
job.error_message = None
|
||||
job.finished_at = job.finished_at or now
|
||||
return len(jobs)
|
||||
@@ -0,0 +1,120 @@
|
||||
"""
|
||||
backend/app/services/kb/markdown.py
|
||||
|
||||
用途:知识库文档 Markdown 读写路径解析与预览生成。
|
||||
依赖:models、services/kb/storage、edkb_system(预览图重写)。
|
||||
逻辑:api/kb/common 与 document_service 共用;不依赖 api 层。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
|
||||
from app import db
|
||||
from app.models import KbDocument, KbDocumentVersion
|
||||
from app.services.kb.storage import resolve_storage_path
|
||||
|
||||
|
||||
def _serialize_version_brief(version: KbDocumentVersion) -> dict:
|
||||
return {
|
||||
'id': version.id,
|
||||
'document_id': version.document_id,
|
||||
'version_no': version.version_no,
|
||||
'status': version.status,
|
||||
'is_current': version.is_current,
|
||||
'source_file_name': version.source_file_name,
|
||||
'source_file_ext': version.source_file_ext,
|
||||
'source_file_size': version.source_file_size,
|
||||
'sha256': version.sha256,
|
||||
'cleaned_file_path': version.cleaned_file_path,
|
||||
'cleaned_preview_path': version.cleaned_preview_path,
|
||||
'error_message': version.error_message,
|
||||
'created_at': version.created_at.isoformat() if version.created_at else None,
|
||||
}
|
||||
|
||||
|
||||
def _ensure_preview_markdown(version: KbDocumentVersion) -> tuple[Path | None, str]:
|
||||
primary = resolve_storage_path(version.cleaned_file_path)
|
||||
preview = resolve_storage_path(version.cleaned_preview_path)
|
||||
preview_exists = bool(preview and preview.exists())
|
||||
primary_exists = bool(primary and primary.exists())
|
||||
|
||||
if preview_exists:
|
||||
preview_content = preview.read_text(encoding='utf-8', errors='ignore')
|
||||
if preview != primary and 'data:image/' not in preview_content:
|
||||
return (preview, 'preview')
|
||||
|
||||
source = primary if primary_exists else preview if preview_exists else None
|
||||
if not source:
|
||||
return (None, 'markdown')
|
||||
|
||||
content = source.read_text(encoding='utf-8', errors='ignore')
|
||||
if 'data:image/' not in content:
|
||||
if source == preview:
|
||||
return (preview, 'preview')
|
||||
if not version.cleaned_preview_path:
|
||||
version.cleaned_preview_path = str(primary)
|
||||
db.session.commit()
|
||||
return (primary, 'markdown')
|
||||
|
||||
from edkb_system.skills.export import _LocalPreviewImageRewriter
|
||||
|
||||
preview = primary.parent / 'document_preview.md'
|
||||
images_dir = primary.parent / 'images_view'
|
||||
if images_dir.exists():
|
||||
shutil.rmtree(images_dir, ignore_errors=True)
|
||||
rewriter = _LocalPreviewImageRewriter(images_dir=images_dir)
|
||||
preview.write_text(rewriter.replace_text(content), encoding='utf-8')
|
||||
version.cleaned_preview_path = str(preview)
|
||||
db.session.commit()
|
||||
return (preview, 'preview')
|
||||
|
||||
|
||||
def resolve_markdown_read_path(version: KbDocumentVersion) -> tuple[Path | None, str]:
|
||||
"""解析 Markdown 读取路径与内容类型(markdown / preview)。"""
|
||||
return _ensure_preview_markdown(version)
|
||||
|
||||
|
||||
def resolve_markdown_write_path(version: KbDocumentVersion) -> Path | None:
|
||||
"""解析 Markdown 写入目标路径。"""
|
||||
primary = resolve_storage_path(version.cleaned_file_path)
|
||||
if primary:
|
||||
return primary
|
||||
preview = resolve_storage_path(version.cleaned_preview_path)
|
||||
if preview and preview.suffix.lower() == '.md':
|
||||
return preview
|
||||
source = resolve_storage_path(version.source_file_path)
|
||||
if source:
|
||||
return source.parent / 'document.md'
|
||||
return None
|
||||
|
||||
|
||||
def markdown_unavailable_message(version: KbDocumentVersion) -> str:
|
||||
"""根据版本状态返回 Markdown 不可用的用户提示。"""
|
||||
status = str(getattr(version, 'status', '') or '').strip().lower()
|
||||
error_message = str(getattr(version, 'error_message', '') or '').strip()
|
||||
if status == 'failed':
|
||||
if error_message:
|
||||
return f'当前文档清洗失败,尚未生成 Markdown。失败原因:{error_message}'
|
||||
return '当前文档清洗失败,尚未生成 Markdown,请重新清洗后重试'
|
||||
if status == 'processing':
|
||||
return '当前文档正在清洗中,暂未生成 Markdown,请稍后再试'
|
||||
if status == 'uploaded':
|
||||
return '当前文档待清洗,暂未生成 Markdown,请先发起清洗'
|
||||
return '当前文档尚未生成可编辑 Markdown'
|
||||
|
||||
|
||||
def serialize_markdown_payload(
|
||||
document: KbDocument,
|
||||
version: KbDocumentVersion,
|
||||
content: str,
|
||||
kind: str,
|
||||
) -> dict:
|
||||
"""组装 Markdown GET/PATCH 响应体。"""
|
||||
return {
|
||||
'document_id': document.id,
|
||||
'title': document.title,
|
||||
'version': _serialize_version_brief(version),
|
||||
'content': content,
|
||||
'kind': kind,
|
||||
}
|
||||
@@ -0,0 +1,589 @@
|
||||
"""
|
||||
backend/app/services/kb/path_upload_service.py
|
||||
|
||||
用途:知识库路径批量上传(path-upload-jobs)业务编排。
|
||||
依赖:models.KbJob、services/kb/storage、knowledge_cleaning.tasks、app.jobs。
|
||||
逻辑:由 api/kb/groups.py 调用;封装 payload 状态机与 staged 文件生命周期。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import shutil
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from posixpath import normpath
|
||||
from typing import Any
|
||||
|
||||
from werkzeug.datastructures import FileStorage
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.jobs import enqueue_kb_job
|
||||
from app.models import KbGroup, KbJob
|
||||
from app.services.kb.document_service import soft_delete_document
|
||||
from app.services.kb.job_lifecycle import serialize_job
|
||||
from app.services.kb.storage import (
|
||||
kb_storage_root,
|
||||
resolve_storage_path,
|
||||
safe_upload_filename,
|
||||
save_upload,
|
||||
)
|
||||
|
||||
|
||||
def sanitize_relative_path(relative_path: str | None, fallback_name: str) -> str:
|
||||
"""
|
||||
规范化并校验相对路径,防止目录穿越。
|
||||
Args:
|
||||
relative_path: 客户端提交的相对路径。
|
||||
fallback_name: 路径为空时的默认文件名。
|
||||
Returns:
|
||||
安全相对路径(/ 分隔)。
|
||||
Raises:
|
||||
ValueError: 路径非法(含 .. 等)。
|
||||
"""
|
||||
raw = str(relative_path or '').replace('\\', '/').strip().lstrip('/')
|
||||
normalized = normpath(raw) if raw else fallback_name
|
||||
normalized = normalized.replace('\\', '/').lstrip('/')
|
||||
if normalized in ('', '.'):
|
||||
normalized = fallback_name
|
||||
if normalized.startswith('../') or normalized == '..':
|
||||
raise ValueError('非法路径')
|
||||
parts = [part for part in normalized.split('/') if part not in ('', '.')]
|
||||
if any(part == '..' for part in parts):
|
||||
raise ValueError('非法路径')
|
||||
if not parts:
|
||||
parts = [fallback_name]
|
||||
safe_parts = [safe_upload_filename(part) for part in parts[:-1]]
|
||||
safe_leaf = safe_upload_filename(parts[-1] or fallback_name)
|
||||
return '/'.join([*safe_parts, safe_leaf]).strip('/') or safe_upload_filename(fallback_name)
|
||||
|
||||
|
||||
def build_path_upload_file_item(
|
||||
relative_path: str | None,
|
||||
original_name: str | None,
|
||||
**extra: Any,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
构造 path-upload payload 中的单文件条目。
|
||||
Args:
|
||||
relative_path: 相对路径(可选)。
|
||||
original_name: 原始文件名(可选)。
|
||||
extra: 覆盖默认字段。
|
||||
Returns:
|
||||
files 数组元素 dict。
|
||||
Raises:
|
||||
ValueError: 路径非法。
|
||||
"""
|
||||
fallback_name = Path(str(original_name or relative_path or '')).name or 'uploaded_file'
|
||||
normalized_path = sanitize_relative_path(relative_path, fallback_name)
|
||||
payload: dict[str, Any] = {
|
||||
'relative_path': normalized_path,
|
||||
'original_name': Path(fallback_name).name or fallback_name,
|
||||
'staged_path': None,
|
||||
'size': None,
|
||||
'sha256': None,
|
||||
'status': 'queued',
|
||||
'error': None,
|
||||
'document_id': None,
|
||||
'version_id': None,
|
||||
}
|
||||
payload.update(extra)
|
||||
return payload
|
||||
|
||||
|
||||
def find_path_upload_file_item(files: list[dict], relative_path: str) -> dict | None:
|
||||
"""在 files 列表中按 relative_path 查找条目。"""
|
||||
for item in files:
|
||||
current = str(item.get('relative_path') or item.get('original_name') or '').strip()
|
||||
if current == relative_path:
|
||||
return item
|
||||
return None
|
||||
|
||||
|
||||
def sync_path_upload_job_payload(job: KbJob, files: list[dict]) -> tuple[dict, dict]:
|
||||
"""
|
||||
根据 files 列表刷新 job.payload_json / result_json 计数。
|
||||
Returns:
|
||||
(payload, result) 更新后的字典副本。
|
||||
"""
|
||||
payload = dict(job.payload_json or {})
|
||||
result = dict(job.result_json or {})
|
||||
selected_paths: list[str] = []
|
||||
for item in files:
|
||||
relative_path = str(item.get('relative_path') or item.get('original_name') or '').strip()
|
||||
if not relative_path:
|
||||
continue
|
||||
root = relative_path.split('/')[0]
|
||||
if root and root not in selected_paths:
|
||||
selected_paths.append(root)
|
||||
payload['files'] = files
|
||||
payload['total_files'] = len(files)
|
||||
payload['staged_count'] = sum(1 for item in files if str(item.get('staged_path') or '').strip())
|
||||
payload['selected_paths'] = selected_paths
|
||||
result['total'] = len(files)
|
||||
result['success'] = sum(1 for item in files if str(item.get('status') or '').lower() == 'success')
|
||||
result['failed'] = sum(1 for item in files if str(item.get('status') or '').lower() == 'failed')
|
||||
result['staged'] = payload['staged_count']
|
||||
result['processed'] = result['success'] + result['failed']
|
||||
job.payload_json = payload
|
||||
job.result_json = result
|
||||
return payload, result
|
||||
|
||||
|
||||
def refresh_path_upload_job_state(job: KbJob) -> None:
|
||||
"""根据 files 进度更新 job.status、progress、message。"""
|
||||
payload = dict(job.payload_json or {})
|
||||
result = dict(job.result_json or {})
|
||||
total = max(int(result.get('total') or payload.get('total_files') or 0), 0)
|
||||
success = int(result.get('success') or 0)
|
||||
failed = int(result.get('failed') or 0)
|
||||
processed = int(result.get('processed') or (success + failed) or 0)
|
||||
files = list(payload.get('files') or [])
|
||||
has_pending = any(
|
||||
str(item.get('status') or '').lower() in ('queued', 'uploading')
|
||||
for item in files
|
||||
)
|
||||
|
||||
payload['current_file'] = ''
|
||||
job.payload_json = payload
|
||||
job.progress = min(int(processed * 100 / total), 100) if total else 100
|
||||
|
||||
if total == 0:
|
||||
job.status = 'cancelled'
|
||||
job.finished_at = datetime.utcnow()
|
||||
job.progress = 100
|
||||
job.message = '路径上传记录为空'
|
||||
job.error_message = None
|
||||
return
|
||||
|
||||
if has_pending or processed < total:
|
||||
job.status = 'staging'
|
||||
job.finished_at = None
|
||||
job.message = f'已上传并提交清洗 {processed}/{total} 个文件'
|
||||
job.error_message = None
|
||||
return
|
||||
|
||||
job.finished_at = datetime.utcnow()
|
||||
job.progress = 100
|
||||
if failed > 0:
|
||||
job.status = 'failed'
|
||||
job.message = f'路径上传完成,成功 {success} 条,失败 {failed} 条'
|
||||
job.error_message = f'部分文件上传失败:{failed} 条'
|
||||
return
|
||||
|
||||
job.status = 'success'
|
||||
job.message = f'路径上传完成,成功 {success} 条'
|
||||
job.error_message = None
|
||||
|
||||
|
||||
def remove_path_upload_staged_file(staged_path: str | None) -> None:
|
||||
"""删除暂存文件并尽量清理空目录。"""
|
||||
candidate = resolve_storage_path(staged_path)
|
||||
if not candidate or not candidate.exists():
|
||||
return
|
||||
try:
|
||||
candidate.unlink()
|
||||
except FileNotFoundError:
|
||||
return
|
||||
stop_dir = kb_storage_root() / 'path_upload_jobs'
|
||||
parent = candidate.parent
|
||||
while parent.exists() and parent != stop_dir and stop_dir in parent.parents:
|
||||
try:
|
||||
parent.rmdir()
|
||||
except OSError:
|
||||
break
|
||||
parent = parent.parent
|
||||
|
||||
|
||||
def get_active_path_upload_job(group_id: int) -> KbJob | None:
|
||||
"""返回分组下未完成的 path_upload 任务(draft/staging/queued/running)。"""
|
||||
return (
|
||||
db.session.query(KbJob)
|
||||
.filter(
|
||||
KbJob.group_id == group_id,
|
||||
KbJob.job_type == 'path_upload',
|
||||
KbJob.status.in_(('draft', 'staging', 'queued', 'running')),
|
||||
)
|
||||
.order_by(KbJob.created_at.desc(), KbJob.id.desc())
|
||||
.first()
|
||||
)
|
||||
|
||||
|
||||
def _parse_file_items_from_body(data: dict) -> list[dict]:
|
||||
"""从请求 JSON 解析 files 列表为 path-upload 条目。"""
|
||||
raw_files = data.get('files') or []
|
||||
files: list[dict] = []
|
||||
if not isinstance(raw_files, list):
|
||||
return files
|
||||
for item in raw_files:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
try:
|
||||
files.append(build_path_upload_file_item(item.get('relative_path'), item.get('original_name')))
|
||||
except ValueError:
|
||||
continue
|
||||
return files
|
||||
|
||||
|
||||
def upsert_path_upload_job_files(job: KbJob, requested_files: list[dict]) -> None:
|
||||
"""合并新文件条目到既有 path-upload job 并刷新状态。"""
|
||||
payload = dict(job.payload_json or {})
|
||||
files = list(payload.get('files') or [])
|
||||
|
||||
for requested_item in requested_files:
|
||||
relative_path = str(requested_item.get('relative_path') or '').strip()
|
||||
if not relative_path:
|
||||
continue
|
||||
existing_item = find_path_upload_file_item(files, relative_path)
|
||||
if existing_item is None:
|
||||
files.append(requested_item)
|
||||
continue
|
||||
if not str(existing_item.get('original_name') or '').strip():
|
||||
existing_item['original_name'] = requested_item.get('original_name')
|
||||
|
||||
sync_path_upload_job_payload(job, files)
|
||||
if job.status in ('draft', 'staging', 'queued', 'running'):
|
||||
refresh_path_upload_job_state(job)
|
||||
|
||||
|
||||
def require_path_upload_job(job_id: int) -> KbJob:
|
||||
"""加载 path_upload 类型 KbJob,不存在则 NotFoundError。"""
|
||||
job = db.session.get(KbJob, job_id)
|
||||
if not job or job.job_type != 'path_upload':
|
||||
raise NotFoundError('路径上传任务不存在')
|
||||
return job
|
||||
|
||||
|
||||
def create_path_upload_job(group_id: int, data: dict, *, user_id: int | None) -> tuple[KbJob, bool]:
|
||||
"""
|
||||
创建或续用 path-upload 任务。
|
||||
Args:
|
||||
group_id: 知识库分组 id。
|
||||
data: 请求 JSON(files、total_files、selected_paths)。
|
||||
user_id: 当前用户 id。
|
||||
Returns:
|
||||
(job, reused_existing)。
|
||||
"""
|
||||
existing_job = get_active_path_upload_job(group_id)
|
||||
files = _parse_file_items_from_body(data)
|
||||
if existing_job:
|
||||
if files:
|
||||
upsert_path_upload_job_files(existing_job, files)
|
||||
return existing_job, True
|
||||
|
||||
total_files = max(int(data.get('total_files') or 0), 0)
|
||||
selected_paths = data.get('selected_paths') or []
|
||||
if not isinstance(selected_paths, list):
|
||||
selected_paths = []
|
||||
|
||||
if files:
|
||||
total_files = len(files)
|
||||
selected_paths = []
|
||||
for item in files:
|
||||
root = str(item.get('relative_path') or '').split('/')[0]
|
||||
if root and root not in selected_paths:
|
||||
selected_paths.append(root)
|
||||
|
||||
job = KbJob(
|
||||
job_type='path_upload',
|
||||
status='draft',
|
||||
group_id=group_id,
|
||||
progress=0,
|
||||
message='等待上传路径文件到后台暂存区',
|
||||
payload_json={
|
||||
'total_files': total_files,
|
||||
'selected_paths': selected_paths,
|
||||
'staged_count': 0,
|
||||
'files': files,
|
||||
},
|
||||
result_json={
|
||||
'total': total_files,
|
||||
'success': 0,
|
||||
'failed': 0,
|
||||
'staged': 0,
|
||||
'processed': 0,
|
||||
},
|
||||
created_by_id=user_id,
|
||||
)
|
||||
db.session.add(job)
|
||||
return job, False
|
||||
|
||||
|
||||
def upload_path_job_file(
|
||||
job: KbJob,
|
||||
*,
|
||||
file_storage: FileStorage,
|
||||
relative_path_raw: str | None,
|
||||
user_id: int | None,
|
||||
) -> KbJob:
|
||||
"""
|
||||
接收单个 staged 文件,写入暂存区并注册文档版本/清洗任务。
|
||||
Raises:
|
||||
ConflictError: 任务状态不允许上传。
|
||||
ValidationError: 缺少文件或路径非法。
|
||||
"""
|
||||
if job.status not in ('draft', 'staging'):
|
||||
raise ConflictError('当前任务不允许继续上传文件')
|
||||
if not file_storage or not file_storage.filename:
|
||||
raise ValidationError('file is required')
|
||||
|
||||
fallback_name = Path(file_storage.filename).name or 'uploaded_file'
|
||||
relative_path = sanitize_relative_path(relative_path_raw, fallback_name)
|
||||
|
||||
staging_root = kb_storage_root() / 'path_upload_jobs' / f'job_{job.id:06d}' / 'staging'
|
||||
target_path = staging_root / Path(relative_path)
|
||||
sha256, file_size = save_upload(file_storage, target_path)
|
||||
|
||||
payload = dict(job.payload_json or {})
|
||||
files = list(payload.get('files') or [])
|
||||
entry = find_path_upload_file_item(files, relative_path)
|
||||
if (
|
||||
entry is not None
|
||||
and str(entry.get('status') or '').lower() == 'success'
|
||||
and entry.get('document_id')
|
||||
and entry.get('version_id')
|
||||
):
|
||||
sync_path_upload_job_payload(job, files)
|
||||
refresh_path_upload_job_state(job)
|
||||
return job
|
||||
|
||||
if entry is None:
|
||||
entry = build_path_upload_file_item(relative_path, fallback_name)
|
||||
files.append(entry)
|
||||
|
||||
entry['original_name'] = fallback_name
|
||||
entry['staged_path'] = str(target_path)
|
||||
entry['size'] = file_size
|
||||
entry['sha256'] = sha256
|
||||
entry['status'] = 'uploading'
|
||||
entry['error'] = None
|
||||
entry['document_id'] = None
|
||||
entry['version_id'] = None
|
||||
payload['current_file'] = relative_path
|
||||
job.status = 'staging'
|
||||
job.started_at = job.started_at or datetime.utcnow()
|
||||
payload, _result = sync_path_upload_job_payload(job, files)
|
||||
job.payload_json = payload
|
||||
job.message = f'正在上传并提交清洗:{relative_path}'
|
||||
|
||||
try:
|
||||
from app.services.knowledge_cleaning.tasks import _register_document_version_from_staged_file
|
||||
|
||||
document, version, _clean_job = _register_document_version_from_staged_file(
|
||||
group_id=job.group_id,
|
||||
relative_path=relative_path,
|
||||
staged_path=target_path,
|
||||
original_name=fallback_name,
|
||||
user_id=user_id,
|
||||
)
|
||||
entry['status'] = 'success'
|
||||
entry['document_id'] = document.id
|
||||
entry['version_id'] = version.id
|
||||
entry['error'] = None
|
||||
except Exception as exc:
|
||||
entry['status'] = 'failed'
|
||||
entry['error'] = str(exc)
|
||||
|
||||
sync_path_upload_job_payload(job, files)
|
||||
refresh_path_upload_job_state(job)
|
||||
return job
|
||||
|
||||
|
||||
def mark_path_job_file_failed(
|
||||
job: KbJob,
|
||||
*,
|
||||
relative_path_raw: str,
|
||||
original_name: str | None,
|
||||
error_message: str,
|
||||
) -> KbJob:
|
||||
"""标记 path-upload 单文件为 failed。"""
|
||||
fallback = Path(original_name or relative_path_raw or 'uploaded_file').name or 'uploaded_file'
|
||||
relative_path = sanitize_relative_path(relative_path_raw, fallback)
|
||||
message = error_message.strip() or '路径文件上传失败'
|
||||
|
||||
payload = dict(job.payload_json or {})
|
||||
files = list(payload.get('files') or [])
|
||||
entry = find_path_upload_file_item(files, relative_path)
|
||||
if entry is None:
|
||||
entry = build_path_upload_file_item(relative_path, original_name)
|
||||
files.append(entry)
|
||||
if str(entry.get('staged_path') or '').strip() and str(entry.get('status') or '').lower() in (
|
||||
'queued',
|
||||
'success',
|
||||
'uploading',
|
||||
):
|
||||
return job
|
||||
|
||||
entry['status'] = 'failed'
|
||||
entry['error'] = message
|
||||
entry['original_name'] = entry.get('original_name') or original_name or Path(relative_path).name
|
||||
sync_path_upload_job_payload(job, files)
|
||||
refresh_path_upload_job_state(job)
|
||||
return job
|
||||
|
||||
|
||||
def finalize_path_upload_job(job: KbJob, *, user_id: int | None) -> tuple[KbJob, int]:
|
||||
"""
|
||||
提交 path-upload 批次(inline_per_file 模式)。
|
||||
Returns:
|
||||
(job, http_status) — 202 或 200。
|
||||
"""
|
||||
if job.status in ('success', 'failed', 'cancelled'):
|
||||
return job, 200
|
||||
if job.status not in ('draft', 'staging'):
|
||||
raise ConflictError('当前任务不允许提交执行')
|
||||
|
||||
payload = dict(job.payload_json or {})
|
||||
files = list(payload.get('files') or [])
|
||||
if not files:
|
||||
raise ValidationError('当前没有可上传的文件')
|
||||
|
||||
staged_files = [item for item in files if str(item.get('staged_path') or '').strip()]
|
||||
if not staged_files:
|
||||
sync_path_upload_job_payload(job, files)
|
||||
refresh_path_upload_job_state(job)
|
||||
if job.status != 'failed':
|
||||
job.status = 'failed'
|
||||
job.message = '当前批次没有成功暂存的文件'
|
||||
job.error_message = '当前批次没有成功暂存的文件'
|
||||
return job, 200
|
||||
|
||||
payload['finalized_at'] = datetime.utcnow().isoformat()
|
||||
job.payload_json = payload
|
||||
job.created_by_id = user_id
|
||||
sync_path_upload_job_payload(job, files)
|
||||
refresh_path_upload_job_state(job)
|
||||
return job, 202
|
||||
|
||||
|
||||
def delete_path_job_file(
|
||||
job: KbJob,
|
||||
*,
|
||||
relative_path_raw: str,
|
||||
user_id: int | None,
|
||||
) -> tuple[KbJob, bool, str]:
|
||||
"""
|
||||
删除 path-upload 单文件记录及暂存/关联文档。
|
||||
Returns:
|
||||
(job, document_deleted, relative_path)。
|
||||
"""
|
||||
relative_path = sanitize_relative_path(
|
||||
relative_path_raw,
|
||||
Path(relative_path_raw).name or 'uploaded_file',
|
||||
)
|
||||
payload = dict(job.payload_json or {})
|
||||
files = list(payload.get('files') or [])
|
||||
entry = find_path_upload_file_item(files, relative_path)
|
||||
if entry is None:
|
||||
raise NotFoundError('路径文件记录不存在')
|
||||
|
||||
remove_path_upload_staged_file(entry.get('staged_path'))
|
||||
document_deleted = soft_delete_document(entry.get('document_id'), user_id)
|
||||
files = [item for item in files if item is not entry]
|
||||
sync_path_upload_job_payload(job, files)
|
||||
if not files:
|
||||
job.status = 'cancelled'
|
||||
job.progress = 100
|
||||
job.finished_at = job.finished_at or datetime.utcnow()
|
||||
job.message = '路径上传记录已清空'
|
||||
job.error_message = None
|
||||
staging_dir = kb_storage_root() / 'path_upload_jobs' / f'job_{job.id:06d}'
|
||||
if staging_dir.exists():
|
||||
shutil.rmtree(staging_dir, ignore_errors=True)
|
||||
return job, document_deleted, relative_path
|
||||
|
||||
|
||||
def retry_failed_path_upload_job(
|
||||
source_job: KbJob,
|
||||
*,
|
||||
relative_paths: list[str] | None,
|
||||
user_id: int | None,
|
||||
) -> KbJob:
|
||||
"""
|
||||
为失败文件创建新的 queued path_upload 任务并入队。
|
||||
Raises:
|
||||
ValidationError: 无可重试文件。
|
||||
ConflictError: 同组已有其他活跃上传任务。
|
||||
"""
|
||||
if not source_job.group_id:
|
||||
raise ValidationError('路径上传任务缺少分组信息')
|
||||
|
||||
existing_job = get_active_path_upload_job(source_job.group_id)
|
||||
if existing_job and existing_job.id != source_job.id:
|
||||
raise ConflictError('有文件正在上传请稍等再试~', details={'job': serialize_job(existing_job)})
|
||||
|
||||
source_payload = dict(source_job.payload_json or {})
|
||||
source_files = list(source_payload.get('files') or [])
|
||||
requested_path_set = {str(item).strip() for item in (relative_paths or []) if str(item).strip()}
|
||||
|
||||
failed_files = [item for item in source_files if str(item.get('status') or '').lower() == 'failed']
|
||||
if requested_path_set:
|
||||
failed_files = [
|
||||
item
|
||||
for item in failed_files
|
||||
if str(item.get('relative_path') or item.get('original_name') or '').strip() in requested_path_set
|
||||
]
|
||||
if not failed_files:
|
||||
raise ValidationError('当前任务没有可重试的失败文件')
|
||||
|
||||
retry_files: list[dict] = []
|
||||
selected_paths: list[str] = []
|
||||
for item in failed_files:
|
||||
staged_path = str(item.get('staged_path') or '').strip()
|
||||
if not staged_path:
|
||||
continue
|
||||
retry_files.append({
|
||||
'relative_path': item.get('relative_path'),
|
||||
'original_name': item.get('original_name'),
|
||||
'staged_path': staged_path,
|
||||
'size': item.get('size'),
|
||||
'sha256': item.get('sha256'),
|
||||
'status': 'queued',
|
||||
'error': None,
|
||||
'document_id': None,
|
||||
'version_id': None,
|
||||
})
|
||||
relative_path = str(item.get('relative_path') or item.get('original_name') or '').strip()
|
||||
if relative_path:
|
||||
root = relative_path.split('/')[0]
|
||||
if root and root not in selected_paths:
|
||||
selected_paths.append(root)
|
||||
|
||||
if not retry_files:
|
||||
raise ValidationError('失败文件暂存内容不存在,无法重试')
|
||||
|
||||
retry_job = KbJob(
|
||||
job_type='path_upload',
|
||||
status='queued',
|
||||
group_id=source_job.group_id,
|
||||
progress=0,
|
||||
message='等待后台重试失败文件',
|
||||
payload_json={
|
||||
'total_files': len(retry_files),
|
||||
'selected_paths': selected_paths,
|
||||
'staged_count': len(retry_files),
|
||||
'source_job_id': source_job.id,
|
||||
'retry_mode': 'failed_only',
|
||||
'retry_relative_paths': list(requested_path_set),
|
||||
'files': retry_files,
|
||||
},
|
||||
result_json={
|
||||
'total': len(retry_files),
|
||||
'success': 0,
|
||||
'failed': 0,
|
||||
'staged': len(retry_files),
|
||||
'source_job_id': source_job.id,
|
||||
},
|
||||
created_by_id=user_id,
|
||||
)
|
||||
db.session.add(retry_job)
|
||||
db.session.flush()
|
||||
enqueue_kb_job(retry_job.id)
|
||||
return retry_job
|
||||
|
||||
|
||||
def require_active_group(group_id: int) -> KbGroup:
|
||||
"""加载活跃知识库分组。"""
|
||||
group = db.session.get(KbGroup, group_id)
|
||||
if not group or not group.is_active:
|
||||
raise NotFoundError('Knowledge base group not found')
|
||||
return group
|
||||
@@ -0,0 +1,73 @@
|
||||
"""
|
||||
backend/app/services/kb/storage.py
|
||||
|
||||
用途:知识库本地文件存储路径解析与上传写入。
|
||||
依赖:Flask current_app、hashlib。
|
||||
逻辑:api/kb/common 与 services/kb/path_upload_service 共用;禁止 import api 层。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
from flask import current_app
|
||||
|
||||
|
||||
def safe_upload_filename(raw_filename: str | None) -> str:
|
||||
"""
|
||||
清洗上传文件名,去除路径分隔与非法字符。
|
||||
Args:
|
||||
raw_filename: 原始文件名。
|
||||
Returns:
|
||||
安全文件名。
|
||||
"""
|
||||
original_name = Path(raw_filename or '').name.strip()
|
||||
if not original_name:
|
||||
return 'uploaded_file'
|
||||
safe_name = re.sub(r'[\\/*?:"<>|]', '_', original_name)
|
||||
return safe_name or 'uploaded_file'
|
||||
|
||||
|
||||
def kb_storage_root() -> Path:
|
||||
"""返回 KB_STORAGE_ROOT 并确保目录存在。"""
|
||||
root = Path(current_app.config.get('KB_STORAGE_ROOT')).resolve()
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
return root
|
||||
|
||||
|
||||
def resolve_storage_path(path_value: str | None) -> Path | None:
|
||||
"""
|
||||
解析存储路径并校验在 KB_STORAGE_ROOT 内。
|
||||
Returns:
|
||||
绝对 Path 或 None(越界/空)。
|
||||
"""
|
||||
if not path_value:
|
||||
return None
|
||||
candidate = Path(path_value).resolve()
|
||||
root = kb_storage_root()
|
||||
try:
|
||||
candidate.relative_to(root)
|
||||
except ValueError:
|
||||
return None
|
||||
return candidate
|
||||
|
||||
|
||||
def save_upload(file_storage, target_path: Path) -> tuple[str, int]:
|
||||
"""
|
||||
流式写入上传文件并计算 sha256。
|
||||
Returns:
|
||||
(sha256_hex, size_bytes)。
|
||||
"""
|
||||
target_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
sha = hashlib.sha256()
|
||||
size = 0
|
||||
with target_path.open('wb') as handle:
|
||||
while True:
|
||||
chunk = file_storage.stream.read(1024 * 1024)
|
||||
if not chunk:
|
||||
break
|
||||
handle.write(chunk)
|
||||
sha.update(chunk)
|
||||
size += len(chunk)
|
||||
return sha.hexdigest(), size
|
||||
@@ -1,10 +1,9 @@
|
||||
"""
|
||||
backend/app/services/knowledge_cleaning/queue_service.py
|
||||
文件用途:知识库任务调度最小实现
|
||||
|
||||
补充能力(2026-05):
|
||||
- recover_stale_running_jobs:回收超时仍处于 running 的后台任务,防止单条卡死阻塞 worker;
|
||||
- process_next_kb_job 在取 queued 任务前会先执行一次超时回收。
|
||||
用途:知识库任务 claim/process 与执行模式调度(worker 侧)。
|
||||
依赖:KbJob、tasks.run_*。
|
||||
逻辑:enqueue 请走 app.jobs.enqueue_*;本模块保留 claim_next_kb_job、process_next_kb_job、recover。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -12,10 +11,11 @@ import logging
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from flask import current_app
|
||||
from sqlalchemy import exists
|
||||
from sqlalchemy.exc import OperationalError
|
||||
|
||||
from app import db
|
||||
from app.models import KbDocumentVersion, KbJob
|
||||
from app.models import KbDocument, KbDocumentVersion, KbJob
|
||||
|
||||
logger = logging.getLogger('kb-worker')
|
||||
_WORD_EXTENSIONS = {'doc', 'docx'}
|
||||
@@ -100,7 +100,7 @@ def recover_stale_running_jobs() -> tuple[int, str]:
|
||||
|
||||
def enqueue_kb_job(job_id: int) -> tuple[bool, str]:
|
||||
"""
|
||||
最小任务调度器:
|
||||
最小任务调度器(内部实现;调用方请优先 app.jobs.enqueue_kb_job / enqueue_clean_job)。
|
||||
- sync: 上传后立即在请求内执行;
|
||||
- worker: 仅保留 queued,等待独立 worker 轮询;
|
||||
- manual: 保留 queued,等待管理台手动执行。
|
||||
@@ -144,9 +144,22 @@ def claim_next_kb_job() -> KbJob | None:
|
||||
now = datetime.utcnow()
|
||||
try:
|
||||
has_running_word_job = _has_running_word_clean_job()
|
||||
missing_version = exists().where(
|
||||
KbDocumentVersion.id == KbJob.document_version_id,
|
||||
)
|
||||
deleted_document = exists().where(
|
||||
KbDocumentVersion.id == KbJob.document_version_id,
|
||||
KbDocument.id == KbDocumentVersion.document_id,
|
||||
KbDocument.is_deleted.is_(True),
|
||||
)
|
||||
candidates = (
|
||||
db.session.query(KbJob)
|
||||
.filter(KbJob.job_type.in_(('path_upload', 'clean', 'sync_dify')), KbJob.status == 'queued')
|
||||
.filter(
|
||||
KbJob.job_type.in_(('path_upload', 'clean', 'sync_dify')),
|
||||
KbJob.status == 'queued',
|
||||
(KbJob.document_version_id.is_(None)) | missing_version,
|
||||
(KbJob.document_version_id.is_(None)) | (~deleted_document),
|
||||
)
|
||||
.order_by(KbJob.created_at.asc(), KbJob.id.asc())
|
||||
.with_for_update(skip_locked=True)
|
||||
.limit(20)
|
||||
|
||||
@@ -9,7 +9,7 @@ import os
|
||||
from flask import current_app
|
||||
|
||||
from app import db
|
||||
from app.env_persistence import persist_env_settings
|
||||
from app.core.config.env_persistence import persist_env_settings
|
||||
from app.models import AppSetting, KbDifySyncRecord, KbGroup, KbJob, KbDocumentVersion
|
||||
|
||||
|
||||
|
||||
@@ -326,7 +326,7 @@ def _register_document_version_from_staged_file(
|
||||
db.session.add(clean_job)
|
||||
db.session.commit()
|
||||
|
||||
from app.services.knowledge_cleaning.queue_service import enqueue_clean_job
|
||||
from app.jobs import enqueue_clean_job
|
||||
|
||||
enqueue_clean_job(clean_job.id)
|
||||
return document, version, clean_job
|
||||
@@ -590,7 +590,7 @@ def run_clean_job(job_id: int) -> tuple[bool, str]:
|
||||
db.session.commit()
|
||||
|
||||
if sync_job_id:
|
||||
from app.services.knowledge_cleaning.queue_service import enqueue_kb_job
|
||||
from app.jobs import enqueue_kb_job
|
||||
|
||||
enqueue_kb_job(sync_job_id)
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ from typing import BinaryIO
|
||||
from minio import Minio
|
||||
from minio.error import S3Error
|
||||
from werkzeug.utils import secure_filename
|
||||
from app.config import config, ACTIVE_ENV_NAME
|
||||
from app.core.config.settings import config, ACTIVE_ENV_NAME
|
||||
|
||||
cfg = config[ACTIVE_ENV_NAME]
|
||||
|
||||
|
||||
@@ -8,7 +8,8 @@ from urllib.parse import quote
|
||||
|
||||
from flask import current_app
|
||||
|
||||
from app.models import ChatLog, db
|
||||
from app import db
|
||||
from app.models import ChatLog
|
||||
from app.services.text2sql import Text2SQLService
|
||||
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ from werkzeug.utils import secure_filename
|
||||
from app import db
|
||||
from app.services.db_sequence import add_and_flush_with_sequence_retry
|
||||
from app.models import KbDocument, KbDocumentVersion, KbGroup, KbJob, ScheduleRun, ScheduleTask
|
||||
from app.services.knowledge_cleaning.queue_service import enqueue_clean_job
|
||||
from app.jobs import enqueue_clean_job
|
||||
|
||||
|
||||
def update_schedule_run_kb_sync_status(
|
||||
|
||||
@@ -8,7 +8,7 @@ from sqlalchemy.orm import joinedload
|
||||
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
from app.response_utils import utc_iso
|
||||
from app.core.response import utc_iso
|
||||
from app.services.schedule.timezone_util import (
|
||||
DEFAULT_SCHEDULE_TIMEZONE,
|
||||
compute_next_run_at,
|
||||
|
||||
@@ -3,7 +3,7 @@ services/shipping_notice/batch_orchestrator.py
|
||||
|
||||
用途:发货通知批次/单票后台编排器。
|
||||
依赖:query_service、task_workflow、dify_executor、shipping_notice.tools、tool_common。
|
||||
逻辑:工作台上传后由后端主导单票调度;批次线程只做任务派发,created 票通过 Dify 完成 AI 解析,其余确定性步骤由后端 auto_progress 推进。
|
||||
逻辑:工作台上传后由后端主导单票调度;批次线程只做任务派发,created 票通过 Dify 完成单票 AI 解析,其余确定性步骤由后端 auto_progress 推进。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -14,12 +14,13 @@ from typing import Any
|
||||
from flask import current_app
|
||||
|
||||
from app import db
|
||||
from app.services.shipping_notice.constants import PH_RPA_EXHAUSTED, PH_RPA_PENDING
|
||||
from app.services.shipping_notice.queue_service import enqueue_shipping_notice_job
|
||||
from app.services.shipping_notice.dify_executor import run_shipping_parse_via_dify
|
||||
from app.services.shipping_notice.query_service import get_batch_by_no, get_task_by_ref, list_sorted_batch_tasks
|
||||
from app.services.shipping_notice.task_workflow import recompute_batch_summary
|
||||
from app.services.shipping_notice.tool_common import auto_progress_enabled, cfg_bool, cfg_int, log_task_event
|
||||
from app.services.shipping_notice.tools import auto_progress
|
||||
from app.services.shipping_notice.tools import auto_progress, submit_decision
|
||||
|
||||
_RUNNING_BATCHES: set[str] = set()
|
||||
_RUNNING_TASKS: set[str] = set()
|
||||
@@ -59,10 +60,17 @@ def _unmark_running(bucket: set[str], key: str) -> None:
|
||||
|
||||
def _should_orchestrate_task(task: Any) -> bool:
|
||||
process_status = str(getattr(task, "process_status", "") or "").strip().lower()
|
||||
pending_reason = str(getattr(task, "pending_human_reason", "") or "").strip().lower()
|
||||
if process_status in _TERMINAL_PROCESS_STATUSES:
|
||||
return False
|
||||
if getattr(task, "review_status", None):
|
||||
return False
|
||||
if (
|
||||
process_status == "waiting_inventory"
|
||||
and not getattr(task, "inventory_lines_json", None)
|
||||
and pending_reason in {"", PH_RPA_PENDING}
|
||||
):
|
||||
return True
|
||||
if getattr(task, "pending_human_reason", None):
|
||||
return False
|
||||
if process_status in {"waiting_inventory", "waiting_upload", "upload_failed"}:
|
||||
@@ -73,10 +81,13 @@ def _should_orchestrate_task(task: Any) -> bool:
|
||||
def _is_retryable_task(task: Any) -> bool:
|
||||
"""判断任务是否允许由批次重试入口重新派发。"""
|
||||
process_status = str(getattr(task, "process_status", "") or "").strip().lower()
|
||||
pending_reason = str(getattr(task, "pending_human_reason", "") or "").strip().lower()
|
||||
if process_status in _TERMINAL_PROCESS_STATUSES:
|
||||
return False
|
||||
if getattr(task, "review_status", None):
|
||||
return False
|
||||
if process_status == "waiting_inventory" and pending_reason in {PH_RPA_PENDING, PH_RPA_EXHAUSTED}:
|
||||
return True
|
||||
if getattr(task, "pending_human_reason", None):
|
||||
return False
|
||||
return True
|
||||
@@ -95,7 +106,8 @@ def _run_single_task(task_no: str) -> dict[str, str | None]:
|
||||
"""
|
||||
后台执行单票任务的一轮推进。
|
||||
|
||||
`created` 先由 Dify 做单票解析,其余状态尝试走 auto_progress;进入人工检查点时自然返回。
|
||||
`created` 先由 Dify 做单票解析;解析完成后和其他可续跑状态统一交给后端 auto_progress。
|
||||
一旦进入人工检查点或等待外部回执状态,本轮自动停止,等待用户或外部系统回写。
|
||||
"""
|
||||
normalized_task_no = _normalize_ref(task_no)
|
||||
if not normalized_task_no:
|
||||
@@ -110,7 +122,11 @@ def _run_single_task(task_no: str) -> dict[str, str | None]:
|
||||
if not _should_orchestrate_task(task):
|
||||
return {
|
||||
"status": "skipped",
|
||||
"message": f"skip process_status={task.process_status or ''}",
|
||||
"message": (
|
||||
f"skip process_status={task.process_status or ''}"
|
||||
f" pending_human_reason={task.pending_human_reason or ''}"
|
||||
f" review_status={task.review_status or ''}"
|
||||
),
|
||||
}
|
||||
|
||||
_refresh_batch_focus(task.task_no)
|
||||
@@ -124,8 +140,27 @@ def _run_single_task(task_no: str) -> dict[str, str | None]:
|
||||
db.session.commit()
|
||||
|
||||
payload: dict[str, Any] = {"task_id": task.task_no, "conversation_id": task.conversation_id}
|
||||
if str(task.process_status or "").strip().lower() == "created":
|
||||
process_status = str(task.process_status or "").strip().lower()
|
||||
pending_reason = str(task.pending_human_reason or "").strip().lower()
|
||||
if (
|
||||
process_status == "waiting_inventory"
|
||||
and not getattr(task, "inventory_lines_json", None)
|
||||
and pending_reason in {"", PH_RPA_PENDING}
|
||||
):
|
||||
payload["mode"] = "auto"
|
||||
result = auto_progress(payload)
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[shipping-orchestrator] rpa-inventory-recheck task_no=%s status=%s message=%s",
|
||||
task.task_no,
|
||||
result.get("status"),
|
||||
str(result.get("message") or "")[:300],
|
||||
)
|
||||
elif process_status == "created":
|
||||
result = run_shipping_parse_via_dify(task.task_no)
|
||||
# Dify 会通过 Tool API 在独立请求中提交 parse_notice;当前 worker session
|
||||
# 可能仍缓存 created 旧对象,必须重新读库后才能决定是否继续 auto_progress。
|
||||
db.session.expire_all()
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[shipping-orchestrator] dify-parse result task_no=%s status=%s process_status_before=%s provider_conversation_id=%s message=%s",
|
||||
@@ -306,7 +341,7 @@ def start_batch_orchestrator(batch_no: str | None) -> bool:
|
||||
|
||||
|
||||
def retry_batch_pending_tasks(batch_no: str | None) -> dict[str, Any]:
|
||||
"""重试批次中仍可自动推进的任务,跳过已终态和人工阻断任务。"""
|
||||
"""重试批次中可恢复的任务;RPA 耗尽态会手动开启新一轮库存导出。"""
|
||||
normalized_batch_no = _normalize_ref(batch_no)
|
||||
if not normalized_batch_no:
|
||||
return {"status": "failed", "message": "batch_no is required"}
|
||||
@@ -320,6 +355,24 @@ def retry_batch_pending_tasks(batch_no: str | None) -> dict[str, Any]:
|
||||
if not _is_retryable_task(task):
|
||||
skipped += 1
|
||||
continue
|
||||
process_status = str(getattr(task, "process_status", "") or "").strip().lower()
|
||||
pending_reason = str(getattr(task, "pending_human_reason", "") or "").strip().lower()
|
||||
if process_status == "waiting_inventory" and pending_reason == PH_RPA_PENDING:
|
||||
result = auto_progress({"task_id": task.task_no, "mode": "auto"})
|
||||
status = str(result.get("status") or "").strip().lower()
|
||||
if status in {"ok", "running", "needs_human"}:
|
||||
started += 1
|
||||
else:
|
||||
skipped += 1
|
||||
continue
|
||||
if process_status == "waiting_inventory" and pending_reason == PH_RPA_EXHAUSTED:
|
||||
result = submit_decision({"task_id": task.task_no, "decision": "retry_rpa"})
|
||||
status = str(result.get("status") or "").strip().lower()
|
||||
if status in {"ok", "running", "needs_human"}:
|
||||
started += 1
|
||||
else:
|
||||
skipped += 1
|
||||
continue
|
||||
if start_task_orchestrator(task.task_no):
|
||||
started += 1
|
||||
else:
|
||||
|
||||
@@ -14,7 +14,7 @@ from typing import Any
|
||||
MAP_JSON = "map_json"
|
||||
SUGGEST_OK = "suggest_ok"
|
||||
AUTO_MAP = "auto_map"
|
||||
# Workspace / Hxops chat fallback only — Dify Agent 主路径应调 auto_progress,勿在画布 HTTP 传此字段
|
||||
# Workspace / Hxops chat fallback only — Dify 正式路径不直接调用主推进 Tool;人工确认后由后端 worker 续跑
|
||||
AUTO_CHAIN_FALLBACK = "auto_chain_fallback"
|
||||
|
||||
# Legacy request field names (read-only compat)
|
||||
@@ -38,6 +38,7 @@ CP_READY_MATCH = "ready_to_match"
|
||||
CP_READY_EXPORT = "ready_to_export"
|
||||
CP_EXPORT_READY = "export_ready"
|
||||
CP_NOTICE_TEXT_EXTRACTION_FAILED = "notice_text_extraction_failed"
|
||||
CP_INVENTORY_SOURCE_REVIEW = "inventory_source_review"
|
||||
CP_EXPORT_GENERATED = "export_generated"
|
||||
CP_UPLOADED = "uploaded"
|
||||
CP_COMPLETED = "completed"
|
||||
@@ -59,6 +60,8 @@ PH_SHORTAGE = "shortage"
|
||||
PH_RPA_EXHAUSTED = "rpa_exhausted"
|
||||
PH_RPA_PENDING = "rpa_pending"
|
||||
PH_INV_UNAVAIL = "inv_unavail"
|
||||
PH_INVENTORY_SOURCE_UNRESOLVED = "inventory_source_unresolved"
|
||||
PH_NOTICE_TEXT_EXTRACTION_FAILED = CP_NOTICE_TEXT_EXTRACTION_FAILED
|
||||
PH_UPLOAD_RPA_FAILED = "upload_rpa_failed"
|
||||
PH_UPLOAD_RPA_PENDING = "upload_rpa_pending"
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ services/shipping_notice/decision_workflow.py
|
||||
|
||||
用途:承接发货通知任务的人工作业决策流转,包括确认、驳回、重匹配、重解析和映射修正。
|
||||
依赖:state_machine、tool_response、query_service、inventory_mapping_workflow、inventory_upload、fulfillment_workflow。
|
||||
逻辑:由 task_workflow 对外转调本文件;本文件在当前任务上下文内执行决策分支,并在必要时回调 auto_progress 或 parse_notice。
|
||||
逻辑:由 task_workflow 对外转调本文件;本文件在当前任务上下文内执行决策分支,并在必要时回调后端 orchestrator。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -28,12 +28,18 @@ from app.services.shipping_notice.inventory_mapping_workflow import (
|
||||
inventory_mapping_checkpoint_response,
|
||||
latest_inventory_column_meta,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_file_store import (
|
||||
active_inventory_file_for_task,
|
||||
linked_task_nos_for_inventory_file,
|
||||
start_inventory_file_linked_tasks,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_upload import (
|
||||
has_uploaded_task_inventory,
|
||||
read_task_inventory_schema_preview,
|
||||
task_inventory_upload_path,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_workflow import ensure_inventory
|
||||
from app.services.shipping_notice.i18n import resolve_lang, t
|
||||
from app.services.shipping_notice.query_service import resolve_task_from_payload, serialize_task_for_tool
|
||||
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition
|
||||
from app.services.shipping_notice.tool_common import (
|
||||
@@ -44,6 +50,13 @@ from app.services.shipping_notice.tool_common import (
|
||||
from app.services.shipping_notice.tool_response import tool_response
|
||||
|
||||
|
||||
def start_task_orchestrator(task_no: str | None) -> bool:
|
||||
"""延迟导入 orchestrator,既打断循环依赖,也保留单测 monkeypatch 入口。"""
|
||||
from app.services.shipping_notice.batch_orchestrator import start_task_orchestrator as _start
|
||||
|
||||
return _start(task_no)
|
||||
|
||||
|
||||
def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
提交人工决策,驱动任务在确认、重解析、重匹配、关闭等分支间流转。
|
||||
@@ -60,14 +73,12 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
if not task:
|
||||
return tool_response(
|
||||
status="failed",
|
||||
message=(
|
||||
"未找到任务。用户说「确认/重新解析/驳回」时禁止 create_task。"
|
||||
"请先 get_task_status(conversation_id=...) 或 submit_decision 带上任务编号。"
|
||||
),
|
||||
message=t("workflow.decision.task_not_found", lang="zh"),
|
||||
)
|
||||
|
||||
decision = str(payload.get("decision") or "").strip().lower()
|
||||
comment = str(payload.get("comment") or "").strip()
|
||||
lang = resolve_lang(payload)
|
||||
|
||||
# [STEP 1] 先处理终止型决策。
|
||||
# reject / close 会直接结束当前任务,不再继续进入库存或出货链路。
|
||||
@@ -78,7 +89,7 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
return tool_response(
|
||||
status="ok",
|
||||
task_id=task.task_no,
|
||||
message="已驳回该发货任务。",
|
||||
message=t("workflow.decision.rejected", lang=lang),
|
||||
data=serialize_task_for_tool(task),
|
||||
)
|
||||
|
||||
@@ -89,7 +100,7 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
return tool_response(
|
||||
status="ok",
|
||||
task_id=task.task_no,
|
||||
message="已关闭该发货任务(可在同一会话重新开新单)。",
|
||||
message=t("workflow.decision.closed", lang=lang),
|
||||
data=serialize_task_for_tool(task),
|
||||
)
|
||||
|
||||
@@ -100,7 +111,7 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
return tool_response(
|
||||
status="failed",
|
||||
task_id=task.task_no,
|
||||
message="库存不足,无法使用 confirm 整单确认。请 reparse_inventory、rematch 或 reject。",
|
||||
message=t("workflow.decision.shortage_confirm_blocked", lang=lang),
|
||||
data=serialize_task_for_tool(task),
|
||||
)
|
||||
|
||||
@@ -120,23 +131,23 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
log_task_event(task, "parse_confirmed", {"comment": comment})
|
||||
db.session.commit()
|
||||
if (not task.inventory_lines_json) and (not has_uploaded_task_inventory(task.task_no)):
|
||||
next_payload = merge_tool_payload(task, payload, extra={"mode": "auto"})
|
||||
if payload_wants_auto_chain_fallback(payload):
|
||||
from app.services.shipping_notice.task_workflow import auto_progress
|
||||
|
||||
return auto_progress(next_payload)
|
||||
return ensure_inventory(next_payload)
|
||||
orchestrator_started = start_task_orchestrator(task.task_no)
|
||||
return tool_response(
|
||||
status="running" if orchestrator_started else "ok",
|
||||
task=task,
|
||||
message=t("workflow.decision.parse_confirmed_running", lang=lang),
|
||||
data=serialize_task_for_tool(task),
|
||||
checkpoint=CP_PARSE_OK,
|
||||
next_required_action=t("workflow.decision.parse_confirmed_wait", lang=lang),
|
||||
forbidden_next_tools=["generate_shipment_excel", "upload_to_freight"],
|
||||
)
|
||||
return tool_response(
|
||||
status="ok",
|
||||
task=task,
|
||||
message=(
|
||||
"发货通知已确认。"
|
||||
"请先处理库存(ensure_inventory / parse_inventory → confirm_inventory_mapping → match_inventory)。"
|
||||
"禁止跳过匹配直接 generate_shipment_excel。"
|
||||
),
|
||||
message=t("workflow.decision.parse_confirmed_next", lang=lang),
|
||||
data=serialize_task_for_tool(task),
|
||||
checkpoint=CP_PARSE_OK,
|
||||
next_required_action="ensure_inventory 或 parse_inventory",
|
||||
next_required_action=t("workflow.decision.parse_confirmed_wait", lang=lang),
|
||||
forbidden_next_tools=["generate_shipment_excel", "upload_to_freight"],
|
||||
)
|
||||
|
||||
@@ -147,59 +158,76 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
return tool_response(
|
||||
status="ok",
|
||||
task_id=task.task_no,
|
||||
message="已确认,可继续生成 Excel 并上传货代系统。",
|
||||
message=t("workflow.decision.matched_confirmed", lang=lang),
|
||||
data=serialize_task_for_tool(task),
|
||||
)
|
||||
|
||||
if task.process_status == "waiting_inventory" or (
|
||||
task.pending_human_reason == PH_RPA_PENDING and not task.inventory_lines_json
|
||||
):
|
||||
follow_payload = merge_tool_payload(task, payload, extra={"mode": "auto"})
|
||||
if payload_wants_auto_chain_fallback(payload):
|
||||
from app.services.shipping_notice.task_workflow import auto_progress
|
||||
|
||||
return auto_progress(follow_payload)
|
||||
return ensure_inventory(follow_payload)
|
||||
orchestrator_started = start_task_orchestrator(task.task_no)
|
||||
return tool_response(
|
||||
status="running" if orchestrator_started else "ok",
|
||||
task=task,
|
||||
message=t("workflow.decision.inventory_preparing", lang=lang),
|
||||
data=serialize_task_for_tool(task),
|
||||
)
|
||||
|
||||
if awaiting_inventory_mapping_confirm(task):
|
||||
lang = str(payload.get("lang") or payload.get("locale") or payload.get("language") or "").strip()
|
||||
return inventory_mapping_checkpoint_response(task, lang=lang or None)
|
||||
|
||||
if task.inventory_lines_json or task.process_status == "inventory_ready":
|
||||
follow_payload = merge_tool_payload(task, payload)
|
||||
if payload_wants_auto_chain_fallback(payload):
|
||||
from app.services.shipping_notice.task_workflow import auto_progress
|
||||
|
||||
return auto_progress(follow_payload)
|
||||
orchestrator_started = start_task_orchestrator(task.task_no)
|
||||
return tool_response(
|
||||
status="ok",
|
||||
status="running" if orchestrator_started else "ok",
|
||||
task=task,
|
||||
message="发货通知已确认,当前任务已进入库存处理阶段,请按当前按钮继续。",
|
||||
message=t("workflow.decision.fulfillment_running", lang=lang),
|
||||
data=serialize_task_for_tool(task),
|
||||
)
|
||||
|
||||
return tool_response(
|
||||
status="failed",
|
||||
task_id=task.task_no,
|
||||
message="当前状态无法使用 confirm。请先完成库存匹配,或使用 confirm_inventory_mapping / reparse。",
|
||||
message=t("workflow.decision.confirm_invalid_state", lang=lang),
|
||||
data=serialize_task_for_tool(task),
|
||||
)
|
||||
|
||||
# [STEP 3] 处理重算型决策。
|
||||
# rematch / confirm_inventory_mapping / correct_inventory_mapping / reparse_inventory
|
||||
# retry_rpa / rematch / confirm_inventory_mapping / correct_inventory_mapping / reparse_inventory
|
||||
# 都是在当前任务基础上回退或重放局部链路,而不是重新 create_task。
|
||||
if decision == "retry_rpa":
|
||||
log_task_event(task, "decision_retry_rpa", {"comment": comment})
|
||||
task.error_message = None
|
||||
db.session.flush()
|
||||
retry_payload = merge_tool_payload(
|
||||
task,
|
||||
payload,
|
||||
extra={"mode": "retry_rpa", "manual_retry_round": True},
|
||||
)
|
||||
return ensure_inventory(retry_payload)
|
||||
|
||||
if decision == "rematch":
|
||||
apply_task_transition(task, TaskTransition.REMATCH_REQUESTED)
|
||||
task.match_status = None
|
||||
task.shortage_json = None
|
||||
task.line_results_json = None
|
||||
log_task_event(task, "decision_rematch", {"comment": comment})
|
||||
db.session.commit()
|
||||
rematch_payload = merge_tool_payload(task, payload)
|
||||
return match_inventory(rematch_payload)
|
||||
orchestrator_started = start_task_orchestrator(task.task_no)
|
||||
return tool_response(
|
||||
status="running" if orchestrator_started else "ok",
|
||||
task=task,
|
||||
message=t("workflow.decision.rematch_running", lang=lang),
|
||||
data=serialize_task_for_tool(task),
|
||||
)
|
||||
|
||||
if decision == "confirm_inventory_mapping":
|
||||
if not awaiting_inventory_mapping_confirm(task):
|
||||
return tool_response(
|
||||
status="failed",
|
||||
task_id=task.task_no,
|
||||
message="当前无需确认库存字段对齐。",
|
||||
message=t("workflow.decision.mapping_not_needed", lang=lang),
|
||||
data=serialize_task_for_tool(task),
|
||||
)
|
||||
meta = latest_inventory_column_meta(task) or {}
|
||||
@@ -216,8 +244,7 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
column_meta=meta,
|
||||
extra_data={
|
||||
"warnings": [
|
||||
"库存表必须包含 Reservation ID 列标题(该列允许为空值)。"
|
||||
"请改用「更正映射」重新选择 Reservation ID 对应的列,或重新上传包含该列的库存 Excel。"
|
||||
t("workflow.decision.mapping_missing_reservation_warning", lang=lang),
|
||||
],
|
||||
},
|
||||
lang=lang or None,
|
||||
@@ -234,17 +261,58 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
field_mapping={str(k): str(v).strip() for k, v in field_mapping.items() if str(v or "").strip()},
|
||||
)
|
||||
apply_task_transition(task, TaskTransition.MAPPING_CONFIRMED)
|
||||
log_task_event(task, "inventory_mapping_confirmed", {"comment": comment})
|
||||
inv_file = active_inventory_file_for_task(task)
|
||||
linked_task_nos = [task.task_no]
|
||||
if inv_file:
|
||||
inv_file.mapping_confirmed = True
|
||||
log_task_event(
|
||||
task,
|
||||
"inventory_mapping_confirmed",
|
||||
{
|
||||
"comment": comment,
|
||||
"confirmed_by_task_no": task.task_no,
|
||||
"inventory_file_no": inv_file.inventory_file_no,
|
||||
},
|
||||
)
|
||||
for link in inv_file.links or []:
|
||||
linked_task = link.task
|
||||
if not link.is_active or not linked_task:
|
||||
continue
|
||||
linked_task_nos.append(linked_task.task_no)
|
||||
if awaiting_inventory_mapping_confirm(linked_task):
|
||||
apply_task_transition(linked_task, TaskTransition.MAPPING_CONFIRMED)
|
||||
log_task_event(
|
||||
linked_task,
|
||||
"inventory_mapping_confirmed",
|
||||
{
|
||||
"comment": comment,
|
||||
"confirmed_by_task_no": task.task_no,
|
||||
"inventory_file_no": inv_file.inventory_file_no,
|
||||
},
|
||||
)
|
||||
else:
|
||||
log_task_event(task, "inventory_mapping_confirmed", {"comment": comment})
|
||||
db.session.commit()
|
||||
next_payload = merge_tool_payload(task, payload)
|
||||
return match_inventory(next_payload)
|
||||
orchestrator_started = (
|
||||
start_inventory_file_linked_tasks(inv_file)
|
||||
if inv_file
|
||||
else start_task_orchestrator(task.task_no)
|
||||
)
|
||||
if inv_file:
|
||||
linked_task_nos = linked_task_nos_for_inventory_file(inv_file)
|
||||
return tool_response(
|
||||
status="running" if orchestrator_started else "ok",
|
||||
task=task,
|
||||
message=t("workflow.decision.mapping_confirmed_running", lang=lang),
|
||||
data={**serialize_task_for_tool(task), "linked_task_nos": linked_task_nos},
|
||||
)
|
||||
|
||||
if decision == "correct_inventory_mapping":
|
||||
if not awaiting_inventory_mapping_confirm(task):
|
||||
return tool_response(
|
||||
status="failed",
|
||||
task_id=task.task_no,
|
||||
message="当前不在库存字段对齐确认步骤,无法更正映射。",
|
||||
message=t("workflow.decision.mapping_correction_invalid_state", lang=lang),
|
||||
data=serialize_task_for_tool(task),
|
||||
)
|
||||
task.inventory_lines_json = None
|
||||
@@ -259,7 +327,7 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
return tool_response(
|
||||
status="failed",
|
||||
task_id=task.task_no,
|
||||
message=f"读取库存表头失败: {exc}",
|
||||
message=t("workflow.decision.read_inventory_preview_failed", lang=lang).format(error=exc),
|
||||
data=serialize_task_for_tool(task),
|
||||
)
|
||||
else:
|
||||
@@ -268,18 +336,15 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"headers": meta.get("headers") or [],
|
||||
"sample_rows": [],
|
||||
"suggested_mapping": meta.get("field_mapping") or {},
|
||||
"note": "无已上传 Excel;请粘贴库存小表或重新上传后 apply_inventory_mapping / parse_inventory。",
|
||||
"note": t("workflow.decision.mapping_preview_note", lang=lang),
|
||||
}
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
task=task,
|
||||
message=(
|
||||
"已回到列映射步骤。请根据 schema_preview 提供新的 map_json,"
|
||||
"再调用 apply_inventory_mapping。"
|
||||
),
|
||||
message=t("workflow.decision.mapping_correction_needed", lang=lang),
|
||||
data={**serialize_task_for_tool(task), "schema_preview": preview},
|
||||
checkpoint=CP_MAP_INFER,
|
||||
next_required_action="apply_inventory_mapping(map_json=...)",
|
||||
next_required_action=t("workflow.decision.mapping_correction_next", lang=lang),
|
||||
forbidden_next_tools=["match_inventory"],
|
||||
stop_agent_turn=True,
|
||||
)
|
||||
@@ -301,15 +366,38 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
return tool_response(
|
||||
status="ok",
|
||||
task_id=task.task_no,
|
||||
message="已清除库存快照,请重新上传或粘贴库存后调用 parse_inventory。",
|
||||
message=t("workflow.decision.inventory_cleared", lang=lang),
|
||||
data=serialize_task_for_tool(task),
|
||||
next_required_action=t("workflow.decision.mapping_correction_next", lang=lang),
|
||||
forbidden_next_tools=["match_inventory", "generate_shipment_excel", "upload_to_freight"],
|
||||
)
|
||||
|
||||
# [STEP 4] 最后处理整单重新解析。
|
||||
# 该分支会复用已有任务号和原始文本,避免产生重复任务。
|
||||
# 整单重解析必须回到 created 并交给后台 Dify 编排,避免启发式兜底直接覆盖 AI 解析。
|
||||
if decision == "reparse":
|
||||
from app.services.shipping_notice.task_workflow import parse_notice
|
||||
task.process_status = "created"
|
||||
task.review_status = None
|
||||
task.pending_human_reason = None
|
||||
task.lines_json = []
|
||||
task.parse_confidence = None
|
||||
task.match_status = None
|
||||
task.shortage_json = None
|
||||
task.line_results_json = None
|
||||
task.inventory_lines_json = None
|
||||
task.error_message = None
|
||||
log_task_event(task, "notice_reparse_requested", {"comment": comment, "source": "dify_required"})
|
||||
db.session.commit()
|
||||
orchestrator_started = start_task_orchestrator(task.task_no)
|
||||
return tool_response(
|
||||
status="running" if orchestrator_started else "ok",
|
||||
task=task,
|
||||
message=f"已提交重新解析任务 {task.task_no},后台将通过 Dify 重新抽取发货通知。",
|
||||
data=serialize_task_for_tool(task),
|
||||
forbidden_next_tools=["match_inventory", "generate_shipment_excel", "upload_to_freight"],
|
||||
)
|
||||
|
||||
return parse_notice({"task_id": task.task_no, "raw_text": task.raw_content or ""})
|
||||
|
||||
return tool_response(status="failed", task_id=task.task_no, message=f"未知 decision: {decision}")
|
||||
return tool_response(
|
||||
status="failed",
|
||||
task_id=task.task_no,
|
||||
message=t("workflow.decision.unknown", lang=lang).format(decision=decision),
|
||||
)
|
||||
@@ -25,24 +25,12 @@ from app.services.shipping_notice.tool_common import cfg_int
|
||||
|
||||
|
||||
def build_single_task_parse_prompt(task_no: str, *, batch_no: str | None = None) -> str:
|
||||
"""构造后台排程器发给 Dify 的单票解析指令。"""
|
||||
pieces = [
|
||||
"你正在处理货代发货通知任务。",
|
||||
f"当前任务编号:{task_no}。",
|
||||
]
|
||||
if batch_no:
|
||||
pieces.append(f"所属批次:{batch_no}。")
|
||||
pieces.extend(
|
||||
[
|
||||
"只允许处理当前这一票,禁止切换任务、禁止整批循环、禁止调用 switch_focus_task。",
|
||||
"先调用 get_task_status 获取当前任务状态和 raw_text。",
|
||||
"如果当前任务已经不是待解析状态,或已经进入人工确认/下游阶段,请直接总结当前状态并结束。",
|
||||
"如果当前任务仍待解析,请基于 raw_text 用 LLM 抽取结构化字段,并调用 parse_notice(structured=...) 落库。",
|
||||
"禁止再次询问用户“是否开始解析”。",
|
||||
"完成后只返回当前票的简短解析结果摘要。",
|
||||
]
|
||||
)
|
||||
return "".join(pieces)
|
||||
"""
|
||||
构造后台排程器发给 Dify 的用户意图短句。
|
||||
|
||||
后台任务号与批次号通过 hxops_context.refs 注入,不能拼入 query,避免 Dify 预处理把 SB-/流程指令误判为切换任务。
|
||||
"""
|
||||
return "解析当前发货通知任务"
|
||||
|
||||
|
||||
def _ensure_chat_session_for_task(task: Any, agent_id: int, title: str) -> ChatSession | None:
|
||||
@@ -86,29 +74,6 @@ def _ensure_chat_session_for_task(task: Any, agent_id: int, title: str) -> ChatS
|
||||
return session
|
||||
|
||||
|
||||
def _update_chat_session_after_stream(
|
||||
session: ChatSession | None,
|
||||
*,
|
||||
provider_conversation_id: str | None,
|
||||
status: str,
|
||||
) -> None:
|
||||
if not session:
|
||||
return
|
||||
provider_id = str(provider_conversation_id or "").strip() or None
|
||||
changed = False
|
||||
if provider_id and session.external_conversation_id != provider_id:
|
||||
session.external_conversation_id = provider_id
|
||||
changed = True
|
||||
if status and session.status != status:
|
||||
session.status = status
|
||||
changed = True
|
||||
session.last_active_at = datetime.utcnow()
|
||||
session.updated_at = datetime.utcnow()
|
||||
changed = True
|
||||
if changed:
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def _log_executor_context(
|
||||
*,
|
||||
task: Any,
|
||||
@@ -160,18 +125,16 @@ def run_shipping_parse_via_dify(task_no: str) -> dict[str, Any]:
|
||||
or str(getattr(task, "conversation_id", "") or "").strip()
|
||||
or task.task_no
|
||||
)
|
||||
provider_conversation_id = (
|
||||
str(getattr(session, "external_conversation_id", "") or "").strip() or None
|
||||
)
|
||||
# 后台编排每票都从新的 Dify provider conversation 开始,避免多票复用前端会话导致上下文串单。
|
||||
provider_conversation_id = None
|
||||
request_id = f"shipping-orch-{task.task_no}"
|
||||
inputs = build_dify_chat_inputs(
|
||||
local_conversation_id,
|
||||
task_id=task.task_no,
|
||||
batch_no=batch_no,
|
||||
entry_mode="orchestrator_parse",
|
||||
user_message="",
|
||||
trigger_source="backend_orchestrator",
|
||||
request_id=request_id,
|
||||
)
|
||||
request_id = f"shipping-orch-{task.task_no}"
|
||||
started_at = time.perf_counter()
|
||||
total_timeout_seconds = _parse_total_timeout_seconds()
|
||||
|
||||
@@ -210,6 +173,7 @@ def run_shipping_parse_via_dify(task_no: str) -> dict[str, Any]:
|
||||
request_id=request_id,
|
||||
session_id=local_conversation_id,
|
||||
inputs=inputs,
|
||||
persist_chat_log=False,
|
||||
)
|
||||
for chunk in stream:
|
||||
if time.perf_counter() - started_at > total_timeout_seconds:
|
||||
@@ -260,11 +224,6 @@ def run_shipping_parse_via_dify(task_no: str) -> dict[str, Any]:
|
||||
break
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
_update_chat_session_after_stream(
|
||||
session,
|
||||
provider_conversation_id=provider_conversation_id,
|
||||
status="error",
|
||||
)
|
||||
if current_app:
|
||||
current_app.logger.exception(
|
||||
"[shipping-dify-executor] exception request_id=%s task_no=%s provider_conversation_id=%s",
|
||||
@@ -274,11 +233,6 @@ def run_shipping_parse_via_dify(task_no: str) -> dict[str, Any]:
|
||||
)
|
||||
return {"status": "failed", "message": str(exc)[:500] or "dify execution failed"}
|
||||
|
||||
_update_chat_session_after_stream(
|
||||
session,
|
||||
provider_conversation_id=provider_conversation_id,
|
||||
status=terminal_status,
|
||||
)
|
||||
refreshed = get_task_by_ref(task.task_no)
|
||||
process_status = str(getattr(refreshed, "process_status", "") or "").strip() if refreshed else ""
|
||||
review_status = str(getattr(refreshed, "review_status", "") or "").strip() if refreshed else ""
|
||||
|
||||
@@ -2,27 +2,27 @@
|
||||
services/shipping_notice/dify_inputs.py
|
||||
|
||||
用途:识别发货通知 Dify Chatflow Agent,并构建会话级 Dify inputs。
|
||||
依赖:agent_resolver、models.ShippingBatch/ShippingTask。
|
||||
依赖:agent_resolver、models.ShippingBatch/ShippingTask、chat.hxops_context。
|
||||
逻辑:由 api/chat 在调用 DifyService.stream_chat 前引用;本模块按会话号解析当前批次/任务焦点,
|
||||
把 Dify 画布需要的 conversation_id、current_batch_no、current_task_no 注入 Start 节点变量。
|
||||
仅补充货代发货场景可识别的 refs,再委托平台级上下文构造器生成 hxops_context。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.models import ShippingBatch, ShippingTask
|
||||
from app.services.shipping_notice.agent_resolver import CHAT_AGENT_NAME
|
||||
from typing import Any
|
||||
|
||||
SHIPPING_CONVERSATION_ID_INPUT = "conversation_id"
|
||||
SHIPPING_CURRENT_BATCH_NO_INPUT = "current_batch_no"
|
||||
SHIPPING_CURRENT_TASK_NO_INPUT = "current_task_no"
|
||||
SHIPPING_ENTRY_MODE_INPUT = "entry_mode"
|
||||
SHIPPING_USER_MESSAGE_INPUT = "user_message"
|
||||
SHIPPING_TRIGGER_SOURCE_INPUT = "trigger_source"
|
||||
from app.models import ShippingBatch, ShippingTask
|
||||
from app.services.chat.hxops_context import HXOPS_CONTEXT_INPUT, build_hxops_context, build_ref
|
||||
from app.services.shipping_notice.agent_resolver import CHAT_AGENT_NAME
|
||||
|
||||
|
||||
def is_shipping_notice_chat_agent(agent) -> bool:
|
||||
"""判断 Agent 记录是否为发货通知聊天 Agent。"""
|
||||
return getattr(agent, "name", None) == CHAT_AGENT_NAME
|
||||
agent_name = str(getattr(agent, "name", None) or "").strip()
|
||||
if agent_name == CHAT_AGENT_NAME:
|
||||
return True
|
||||
normalized_name = agent_name.replace(" ", "")
|
||||
return "发货通知" in normalized_name and "Agent" in normalized_name
|
||||
|
||||
|
||||
def _latest_batch_for_conversation(conversation_id: str) -> ShippingBatch | None:
|
||||
@@ -50,53 +50,63 @@ def _latest_task_for_conversation(conversation_id: str) -> ShippingTask | None:
|
||||
)
|
||||
|
||||
|
||||
def _build_hxops_refs(*, task: str, batch: str) -> list[dict[str, str]]:
|
||||
"""构建货代发货 Agent 当前已知业务对象锚点。"""
|
||||
return [
|
||||
build_ref("task", task),
|
||||
build_ref("batch", batch),
|
||||
]
|
||||
|
||||
|
||||
def build_dify_chat_inputs(
|
||||
conversation_id: str | None = None,
|
||||
*,
|
||||
task_id: str | None = None,
|
||||
batch_no: str | None = None,
|
||||
entry_mode: str | None = None,
|
||||
user_message: str | None = None,
|
||||
trigger_source: str | None = None,
|
||||
) -> dict[str, str]:
|
||||
request_id: str | None = None,
|
||||
locale: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
构建发货通知 Dify Chatflow inputs。
|
||||
|
||||
OpenAPI 工具已在 Dify 侧配置 Server URL 与 Authorization / X-Integration-Key,
|
||||
无需再注入 HXOPS_TOOLS_API_BASE;这里只补会话级上下文,供 Dify 画布稳定读取当前 task/batch。
|
||||
无需再注入 HXOPS_TOOLS_API_BASE;这里只补会话级上下文,供 Dify 画布通过 refs 稳定定位当前 task/batch。
|
||||
"""
|
||||
conv_id = str(conversation_id or "").strip()
|
||||
if not conv_id:
|
||||
return {}
|
||||
|
||||
explicit_task_no = str(task_id or "").strip().upper()
|
||||
explicit_batch_no = str(batch_no or "").strip().upper()
|
||||
explicit_task = str(task_id or "").strip().upper()
|
||||
explicit_batch = str(batch_no or "").strip().upper()
|
||||
|
||||
batch = _latest_batch_for_conversation(conv_id)
|
||||
task = _latest_task_for_conversation(conv_id)
|
||||
|
||||
current_task_no = explicit_task_no
|
||||
if not current_task_no and batch and batch.current_focus_task_no:
|
||||
current_task_no = str(batch.current_focus_task_no or "").strip().upper()
|
||||
elif not current_task_no and task and task.task_no:
|
||||
current_task_no = str(task.task_no or "").strip().upper()
|
||||
focus_task = explicit_task
|
||||
if not focus_task and batch and batch.current_focus_task_no:
|
||||
focus_task = str(batch.current_focus_task_no or "").strip().upper()
|
||||
elif not focus_task and task and task.task_no:
|
||||
focus_task = str(task.task_no or "").strip().upper()
|
||||
|
||||
current_batch_no = explicit_batch_no
|
||||
if not current_batch_no and batch and batch.batch_no:
|
||||
current_batch_no = str(batch.batch_no or "").strip().upper()
|
||||
focus_batch = explicit_batch
|
||||
if not focus_batch and batch and batch.batch_no:
|
||||
focus_batch = str(batch.batch_no or "").strip().upper()
|
||||
elif (
|
||||
not current_batch_no
|
||||
not focus_batch
|
||||
and task
|
||||
and getattr(task, "batch", None) is not None
|
||||
and getattr(task.batch, "batch_no", None)
|
||||
):
|
||||
current_batch_no = str(task.batch.batch_no or "").strip().upper()
|
||||
focus_batch = str(task.batch.batch_no or "").strip().upper()
|
||||
|
||||
return {
|
||||
SHIPPING_ENTRY_MODE_INPUT: str(entry_mode or "").strip(),
|
||||
SHIPPING_CONVERSATION_ID_INPUT: conv_id,
|
||||
SHIPPING_CURRENT_BATCH_NO_INPUT: current_batch_no,
|
||||
SHIPPING_CURRENT_TASK_NO_INPUT: current_task_no,
|
||||
SHIPPING_USER_MESSAGE_INPUT: str(user_message or "").strip(),
|
||||
SHIPPING_TRIGGER_SOURCE_INPUT: str(trigger_source or "").strip(),
|
||||
}
|
||||
hxops_context = build_hxops_context(
|
||||
session_id=conv_id,
|
||||
request_id=request_id,
|
||||
trigger_source=trigger_source,
|
||||
locale=locale,
|
||||
refs=_build_hxops_refs(task=focus_task, batch=focus_batch),
|
||||
)
|
||||
if not hxops_context:
|
||||
return {}
|
||||
return {HXOPS_CONTEXT_INPUT: hxops_context}
|
||||
Loaded 100 of 258 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user