Merge branch 'dev' into hugo
This commit is contained in:
commit
d5928b42f3
63 files changed
+5759
-1493
No files matched your search
@@ -91,6 +91,8 @@ def create_app(config_name='default'):
|
||||
_apply_persisted_settings(app)
|
||||
from app.services.schedule.scheduler_service import start_scheduler
|
||||
start_scheduler(app)
|
||||
from app.services.fixed_assets_snapshot import FixedAssetsSnapshotService
|
||||
FixedAssetsSnapshotService.start_worker(app)
|
||||
from app.cli.faq_commands import init_app as init_faq_cli
|
||||
init_faq_cli(app)
|
||||
|
||||
|
||||
+203
-25
@@ -6,7 +6,7 @@ backend/app/api/admin.py
|
||||
逻辑:供前端 Admin 控制台调用;创建/编辑用户时委托 user._sync_casdoor_* 与 IdP 保持同步。
|
||||
"""
|
||||
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
|
||||
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
|
||||
@@ -18,6 +18,7 @@ from sqlalchemy.orm import joinedload
|
||||
from datetime import datetime, timedelta
|
||||
import csv
|
||||
import io
|
||||
import math
|
||||
import re
|
||||
import requests
|
||||
import uuid
|
||||
@@ -41,6 +42,29 @@ def _raise_user_integrity_conflict(exc: IntegrityError) -> None:
|
||||
raise ConflictError('Username already exists', code='USER.USERNAME_EXISTS')
|
||||
raise ConflictError('Data uniqueness conflict', code='USER.UNIQUENESS_CONFLICT')
|
||||
|
||||
def _assert_user_unique_fields(exclude_user_id: int | None, **fields: str | None) -> None:
|
||||
"""
|
||||
校验用户唯一字段(邮箱、工号、手机号)不与其它账号冲突。
|
||||
核心逻辑:对传入的非 None 字段查询 User 表;编辑时 exclude_user_id 排除当前用户。
|
||||
@param exclude_user_id: 编辑场景传当前用户 id;创建场景传 None
|
||||
@param fields: email / employee_id / phone_number 等待校验值
|
||||
@raises ConflictError: 唯一字段已被占用
|
||||
"""
|
||||
checks = (
|
||||
('email', 'USER.EMAIL_EXISTS', 'Email already exists'),
|
||||
('employee_id', 'USER.EMPLOYEE_ID_EXISTS', 'Employee ID already exists'),
|
||||
('phone_number', 'USER.PHONE_EXISTS', 'Phone number already exists'),
|
||||
)
|
||||
for field, code, message in checks:
|
||||
value = fields.get(field)
|
||||
if value is None:
|
||||
continue
|
||||
query = db.session.query(User.id).filter(getattr(User, field) == value)
|
||||
if exclude_user_id is not None:
|
||||
query = query.filter(User.id != exclude_user_id)
|
||||
if query.first():
|
||||
raise ConflictError(message, code=code, details={'field': field})
|
||||
|
||||
def _empty_to_none(value):
|
||||
if value is None:
|
||||
return None
|
||||
@@ -564,13 +588,19 @@ def create_user():
|
||||
email = _empty_to_none(data.get('email'))
|
||||
if not _is_valid_email(email):
|
||||
raise AppError(code='USER.EMAIL_INVALID', message='Invalid email format', http_status=400, details={'field': 'email'})
|
||||
_assert_user_unique_fields(
|
||||
None,
|
||||
email=email,
|
||||
employee_id=_empty_to_none(data.get('employee_id')),
|
||||
phone_number=_empty_to_none(data.get('phone_number')),
|
||||
)
|
||||
user = User(username=data['username'], email=email, department=_empty_to_none(data.get('department')), role=data.get('role', 'user'), status=data.get('status', 'active'), real_name=_empty_to_none(data.get('real_name')), employee_id=_empty_to_none(data.get('employee_id')), phone_number=_empty_to_none(data.get('phone_number')))
|
||||
user.set_password(data['password'])
|
||||
if data.get('agent_ids'):
|
||||
agents = db.session.query(Agent).filter(Agent.id.in_(data['agent_ids'])).all()
|
||||
user.agents = agents
|
||||
db.session.add(user)
|
||||
try:
|
||||
if data.get('agent_ids'):
|
||||
agents = db.session.query(Agent).filter(Agent.id.in_(data['agent_ids'])).all()
|
||||
user.agents = agents
|
||||
user_api._sync_casdoor_create_user(
|
||||
username=user.username,
|
||||
password=data['password'],
|
||||
@@ -597,7 +627,7 @@ def create_user():
|
||||
def update_user(id):
|
||||
"""
|
||||
管理端编辑用户:资料仅写本地库;仅改密时同步 Casdoor set-password。
|
||||
核心逻辑:应用本地字段 →(有 new_password 时)_sync_casdoor_update_user → commit。
|
||||
核心逻辑:唯一字段预校验 → 应用本地字段与 agent_ids →(有 new_password 时)_sync_casdoor_update_user → commit。
|
||||
Request JSON: email, department, role, status, password 等;password 为空表示不改密
|
||||
Returns:
|
||||
{ status: ok };Casdoor 改密/唯一约束失败时抛出 AppError/ConflictError
|
||||
@@ -611,19 +641,25 @@ def update_user(id):
|
||||
email = _empty_to_none(data.get('email'))
|
||||
if email is not None and (not _is_valid_email(email)):
|
||||
raise AppError(code='USER.EMAIL_INVALID', message='Invalid email format', http_status=400, details={'field': 'email'})
|
||||
unique_updates = {
|
||||
field: _empty_to_none(data[field])
|
||||
for field in ('email', 'employee_id', 'phone_number')
|
||||
if field in data
|
||||
}
|
||||
_assert_user_unique_fields(id, **unique_updates)
|
||||
new_password = _empty_to_none(data.get('password'))
|
||||
for k in ['email', 'department', 'role', 'status', 'real_name', 'employee_id', 'phone_number']:
|
||||
if k in data:
|
||||
if k in ['email', 'department', 'real_name', 'employee_id', 'phone_number']:
|
||||
setattr(user, k, _empty_to_none(data[k]))
|
||||
else:
|
||||
setattr(user, k, data[k])
|
||||
if new_password:
|
||||
user.set_password(new_password)
|
||||
if 'agent_ids' in data:
|
||||
agents = db.session.query(Agent).filter(Agent.id.in_(data['agent_ids'])).all()
|
||||
user.agents = agents
|
||||
try:
|
||||
for k in ['email', 'department', 'role', 'status', 'real_name', 'employee_id', 'phone_number']:
|
||||
if k in data:
|
||||
if k in ['email', 'department', 'real_name', 'employee_id', 'phone_number']:
|
||||
setattr(user, k, _empty_to_none(data[k]))
|
||||
else:
|
||||
setattr(user, k, data[k])
|
||||
if new_password:
|
||||
user.set_password(new_password)
|
||||
if 'agent_ids' in data:
|
||||
agents = db.session.query(Agent).filter(Agent.id.in_(data['agent_ids'])).all()
|
||||
user.agents = agents
|
||||
if new_password:
|
||||
user_api._sync_casdoor_update_user(user, new_password=new_password)
|
||||
db.session.commit()
|
||||
@@ -804,18 +840,23 @@ def reject_request(id):
|
||||
def list_quick_questions():
|
||||
"""
|
||||
列出全局常用问题(含 FAQ 缓存字段)。
|
||||
@returns JSON 数组,每项含 answer/cache_enabled/hit_count 等扩展字段
|
||||
@query stale_only - 可选,true 时仅返回待复审(stale_at 非空)条目
|
||||
@returns JSON 数组,每项含 answer/cache_enabled/hit_count/stale_* 等扩展字段
|
||||
"""
|
||||
qqs = (
|
||||
stale_only = str(request.args.get('stale_only', '')).lower() in {'1', 'true', 'yes'}
|
||||
query = (
|
||||
db.session.query(QuickQuestion)
|
||||
.filter(QuickQuestion.user_id.is_(None))
|
||||
.order_by(QuickQuestion.sort_order.asc(), QuickQuestion.id.asc())
|
||||
.all()
|
||||
)
|
||||
if stale_only:
|
||||
query = query.filter(QuickQuestion.stale_at.isnot(None))
|
||||
qqs = query.all()
|
||||
res = []
|
||||
for q in qqs:
|
||||
agent = db.session.get(Agent, q.agent_id)
|
||||
res.append(_serialize_admin_quick_question(q, agent.name if agent else 'Unknown'))
|
||||
stale_doc = db.session.get(KbDocument, q.stale_kb_document_id) if q.stale_kb_document_id else None
|
||||
res.append(_serialize_admin_quick_question(q, agent.name if agent else 'Unknown', stale_doc))
|
||||
return jsonify(res)
|
||||
|
||||
|
||||
@@ -859,11 +900,16 @@ def _parse_expires_at(raw_value) -> datetime | None:
|
||||
raise ValidationError('Invalid expires_at format')
|
||||
|
||||
|
||||
def _serialize_admin_quick_question(q: QuickQuestion, agent_name: str) -> dict:
|
||||
def _serialize_admin_quick_question(
|
||||
q: QuickQuestion,
|
||||
agent_name: str,
|
||||
stale_kb_document: KbDocument | None = None,
|
||||
) -> dict:
|
||||
"""
|
||||
序列化全局常用问题供管理端展示。
|
||||
@param q - QuickQuestion 实例
|
||||
@param agent_name - 所属应用名称
|
||||
@param stale_kb_document - 触发待复审的 KB 文档(可选)
|
||||
@returns 可 JSON 化的字典
|
||||
"""
|
||||
return {
|
||||
@@ -880,6 +926,11 @@ def _serialize_admin_quick_question(q: QuickQuestion, agent_name: str) -> dict:
|
||||
'sort_order': q.sort_order,
|
||||
'expires_at': q.expires_at.isoformat() if q.expires_at else None,
|
||||
'updated_at': q.updated_at.isoformat() if getattr(q, 'updated_at', None) else None,
|
||||
'source_kb_document_ids': q.source_kb_document_ids if isinstance(q.source_kb_document_ids, list) else [],
|
||||
'stale_at': q.stale_at.isoformat() if getattr(q, 'stale_at', None) else None,
|
||||
'stale_reason': q.stale_reason,
|
||||
'stale_kb_document_id': q.stale_kb_document_id,
|
||||
'stale_kb_document_title': stale_kb_document.title if stale_kb_document else None,
|
||||
}
|
||||
|
||||
|
||||
@@ -908,6 +959,14 @@ def _apply_quick_question_payload(qq: QuickQuestion, data: dict, *, require_answ
|
||||
qq.is_enabled = bool(data['is_enabled'])
|
||||
if 'expires_at' in data:
|
||||
qq.expires_at = _parse_expires_at(data['expires_at'])
|
||||
if 'retriever_resources' in data and isinstance(data.get('retriever_resources'), list):
|
||||
from app.services.faq_kb_invalidation import apply_retriever_resources_to_faq
|
||||
|
||||
apply_retriever_resources_to_faq(qq, data['retriever_resources'])
|
||||
if data.get('clear_stale'):
|
||||
from app.services.faq_kb_invalidation import clear_faq_stale
|
||||
|
||||
clear_faq_stale(qq)
|
||||
|
||||
if qq.cache_enabled and not str(qq.answer or '').strip():
|
||||
raise ValidationError('启用 FAQ 缓存时必须填写标准答案')
|
||||
@@ -925,6 +984,10 @@ def create_quick_question():
|
||||
data = request.get_json() or {}
|
||||
qq = QuickQuestion(user_id=None)
|
||||
_apply_quick_question_payload(qq, data, require_answer=True)
|
||||
if isinstance(data.get('retriever_resources'), list):
|
||||
from app.services.faq_kb_invalidation import apply_retriever_resources_to_faq
|
||||
|
||||
apply_retriever_resources_to_faq(qq, data['retriever_resources'])
|
||||
qq.updated_at = datetime.utcnow()
|
||||
db.session.add(qq)
|
||||
db.session.commit()
|
||||
@@ -1027,6 +1090,7 @@ def promote_faq_candidate():
|
||||
|
||||
aliases = [q for q in (candidate.get('sample_queries') or []) if normalize_faq_query(q) != q_norm]
|
||||
|
||||
retriever_resources = candidate.get('retriever_resources') if isinstance(candidate.get('retriever_resources'), list) else None
|
||||
qq = QuickQuestion(
|
||||
user_id=None,
|
||||
agent_id=int(agent_id),
|
||||
@@ -1036,10 +1100,13 @@ def promote_faq_candidate():
|
||||
aliases=aliases or None,
|
||||
cache_enabled=True,
|
||||
is_enabled=True,
|
||||
retriever_resources=candidate.get('retriever_resources') if isinstance(candidate.get('retriever_resources'), list) else None,
|
||||
retriever_resources=retriever_resources,
|
||||
sort_order=int(data.get('sort_order') or 0),
|
||||
updated_at=datetime.utcnow(),
|
||||
)
|
||||
from app.services.faq_kb_invalidation import apply_retriever_resources_to_faq
|
||||
|
||||
apply_retriever_resources_to_faq(qq, retriever_resources)
|
||||
db.session.add(qq)
|
||||
db.session.flush()
|
||||
if not HotFaqCandidateStore.mark_promoted(int(agent_id), q_norm, qq.id):
|
||||
@@ -1070,13 +1137,59 @@ def dismiss_faq_candidate():
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
|
||||
USAGE_BY_USER_TOP_LIMIT = 50
|
||||
|
||||
|
||||
@admin_bp.route('/reports/usage', methods=['GET'])
|
||||
@require_admin
|
||||
def usage_report():
|
||||
"""
|
||||
聊天使用分析:按应用汇总全部;按用户仅 TOP N(默认 50)并支持分页。
|
||||
Query: user_page(默认 1)、user_page_size(默认 10,最大 50)
|
||||
"""
|
||||
total = db.session.query(ChatLog).count()
|
||||
by_user = db.session.query(User.username, func.count(ChatLog.id)).join(ChatLog).group_by(User.username).all()
|
||||
by_agent = db.session.query(Agent.name, func.count(ChatLog.id)).join(ChatLog).group_by(Agent.name).all()
|
||||
return jsonify({'total': total, 'by_user': [{'username': u, 'count': c} for u, c in by_user], 'by_agent': [{'agent': a, 'count': c} for a, c in by_agent]})
|
||||
by_agent = (
|
||||
db.session.query(Agent.name, func.count(ChatLog.id))
|
||||
.join(ChatLog)
|
||||
.group_by(Agent.name)
|
||||
.order_by(desc(func.count(ChatLog.id)), Agent.name)
|
||||
.all()
|
||||
)
|
||||
try:
|
||||
user_page = int(request.args.get('user_page', 1))
|
||||
except (TypeError, ValueError):
|
||||
user_page = 1
|
||||
try:
|
||||
user_page_size = int(request.args.get('user_page_size', 10))
|
||||
except (TypeError, ValueError):
|
||||
user_page_size = 10
|
||||
user_page = max(1, user_page)
|
||||
user_page_size = max(1, min(user_page_size, USAGE_BY_USER_TOP_LIMIT))
|
||||
|
||||
by_user_top = (
|
||||
db.session.query(User.username, func.count(ChatLog.id))
|
||||
.join(ChatLog)
|
||||
.group_by(User.username)
|
||||
.order_by(desc(func.count(ChatLog.id)), User.username)
|
||||
.limit(USAGE_BY_USER_TOP_LIMIT)
|
||||
.all()
|
||||
)
|
||||
user_total = len(by_user_top)
|
||||
user_pages = max(1, math.ceil(user_total / user_page_size)) if user_total else 1
|
||||
user_page = min(user_page, user_pages)
|
||||
offset = (user_page - 1) * user_page_size
|
||||
by_user_page = by_user_top[offset:offset + user_page_size]
|
||||
|
||||
return jsonify({
|
||||
'total': total,
|
||||
'by_user': [{'username': u, 'count': c} for u, c in by_user_page],
|
||||
'by_agent': [{'agent': a, 'count': c} for a, c in by_agent],
|
||||
'user_total': user_total,
|
||||
'user_page': user_page,
|
||||
'user_page_size': user_page_size,
|
||||
'user_pages': user_pages,
|
||||
'user_top_limit': USAGE_BY_USER_TOP_LIMIT,
|
||||
})
|
||||
|
||||
@admin_bp.route('/reports/feedback', methods=['GET'])
|
||||
@require_admin
|
||||
@@ -1151,9 +1264,74 @@ def count_general_feedbacks_report():
|
||||
total = query.count()
|
||||
return jsonify({'table': 'general_feedbacks', 'total': int(total)})
|
||||
|
||||
def _chat_logs_report_query():
|
||||
"""
|
||||
聊天日志报表查询:关联用户与应用,供管理后台数据报表展示。
|
||||
核心逻辑:ChatLog JOIN User、Agent,按创建时间倒序。
|
||||
"""
|
||||
return (
|
||||
db.session.query(
|
||||
ChatLog,
|
||||
User.username.label('username'),
|
||||
Agent.name.label('agent_name'),
|
||||
)
|
||||
.join(User, User.id == ChatLog.user_id)
|
||||
.join(Agent, Agent.id == ChatLog.agent_id)
|
||||
)
|
||||
|
||||
|
||||
def _serialize_chat_log_report_row(log: ChatLog, username: str | None, agent_name: str | None) -> dict:
|
||||
"""
|
||||
将 ChatLog 及关联字段序列化为报表行(隐藏 run_id / 原始 ID 类外键列)。
|
||||
保留 id 供前端批量删除使用,默认不在表格列中展示。
|
||||
"""
|
||||
created_at = log.created_at.isoformat() if log.created_at else None
|
||||
return {
|
||||
'id': log.id,
|
||||
'agent_name': agent_name or '',
|
||||
'username': username 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,
|
||||
}
|
||||
|
||||
|
||||
def _apply_chat_logs_report_filters(query):
|
||||
"""
|
||||
对聊天日志报表查询应用列筛选(支持展示列名与 ChatLog 字段名)。
|
||||
"""
|
||||
reserved = {'limit', 'offset', 'page', 'page_size'}
|
||||
for key, value in request.args.items():
|
||||
if key in reserved or not value:
|
||||
continue
|
||||
if key == 'agent_name':
|
||||
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 hasattr(ChatLog, key):
|
||||
col = getattr(ChatLog, key)
|
||||
query = query.filter(col.cast(db.String).ilike(f'%{value}%'))
|
||||
return query
|
||||
|
||||
|
||||
def _list_chat_logs_report():
|
||||
"""管理后台聊天日志报表数据列表(最多 100 条,支持列筛选)。"""
|
||||
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]
|
||||
return jsonify(rows)
|
||||
|
||||
|
||||
@admin_bp.route('/database/<table>', methods=['GET'])
|
||||
@require_admin
|
||||
def get_table_data(table):
|
||||
if table == 'chat_logs':
|
||||
return _list_chat_logs_report()
|
||||
|
||||
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:
|
||||
|
||||
@@ -1031,6 +1031,7 @@ def get_chat_query_preview(chat_log_id: int):
|
||||
page_size=page_size,
|
||||
agent=g.current_agent,
|
||||
total_count=total_count,
|
||||
user_context=Text2SQLService._normalize_user_context(g.current_user),
|
||||
)
|
||||
if columns == ["Error"]:
|
||||
raise AppError(code='CHAT.QUERY_PREVIEW_FAILED', message=str(rows[0][0] if rows and rows[0] else 'query preview failed'), http_status=500)
|
||||
|
||||
@@ -13,6 +13,74 @@ internal_jobs_bp = Blueprint('internal_jobs', __name__)
|
||||
def run_internal_job(name: str):
|
||||
key = name.strip().lower()
|
||||
data = request.get_json(silent=True) or {}
|
||||
if key in {'fixed-assets-snapshot', 'fixed_assets_snapshot', 'fixedassets'}:
|
||||
from app.services.fixed_assets_snapshot import FixedAssetsSnapshotService
|
||||
|
||||
summary = FixedAssetsSnapshotService.sync_once(reason='internal_api', attempt=1)
|
||||
row_count = int(summary.get('row_count') or 0)
|
||||
return jsonify({
|
||||
'summary': {
|
||||
'total_count': row_count,
|
||||
'success_count': row_count,
|
||||
'failed_count': 0,
|
||||
'skipped_count': 0,
|
||||
},
|
||||
'details': [summary],
|
||||
'errors': [],
|
||||
'step_logs': [
|
||||
{
|
||||
'step': 'fixed_assets_snapshot_sync',
|
||||
'status': 'success',
|
||||
'detail': {
|
||||
'version': summary.get('current_version'),
|
||||
'row_count': row_count,
|
||||
},
|
||||
}
|
||||
],
|
||||
})
|
||||
if key in {'faq-aggregate-hot', 'faq_hot_aggregate', 'faq-hot-aggregate'}:
|
||||
from app.services.hot_faq_aggregator import HotFaqAggregator
|
||||
|
||||
schedule_task_id = data.get('schedule_task_id')
|
||||
agent_id = data.get('agent_id')
|
||||
if schedule_task_id:
|
||||
task = db.session.get(ScheduleTask, int(schedule_task_id))
|
||||
if task and task.dify_agent_id:
|
||||
agent_id = task.dify_agent_id
|
||||
result = HotFaqAggregator.aggregate_hot_faq_candidates(
|
||||
agent_id=int(agent_id) if agent_id else None,
|
||||
dry_run=False,
|
||||
)
|
||||
if not result.get('enabled'):
|
||||
message = str(result.get('message') or 'FAQ_HOT_ENABLED is false')
|
||||
return jsonify({
|
||||
'summary': {'total_count': 0, 'success_count': 0, 'failed_count': 0, 'skipped_count': 1},
|
||||
'details': [],
|
||||
'errors': [message],
|
||||
'step_logs': [{'step': 'faq_hot_aggregate', 'status': 'skipped', 'detail': {'message': message}}],
|
||||
})
|
||||
promoted = int(result.get('promoted_count') or 0)
|
||||
skipped = int(result.get('skipped_count') or 0)
|
||||
total = max(promoted + skipped, 1)
|
||||
return jsonify({
|
||||
'summary': {
|
||||
'total_count': total,
|
||||
'success_count': promoted,
|
||||
'failed_count': 0,
|
||||
'skipped_count': skipped,
|
||||
},
|
||||
'details': (result.get('candidates') or [])[:20],
|
||||
'errors': [],
|
||||
'step_logs': [{
|
||||
'step': 'faq_hot_aggregate',
|
||||
'status': 'success',
|
||||
'detail': {
|
||||
'scanned_logs': result.get('scanned_logs'),
|
||||
'promoted_count': promoted,
|
||||
'skipped_count': skipped,
|
||||
},
|
||||
}],
|
||||
})
|
||||
run_no = str(data.get('run_no') or '').strip()
|
||||
schedule_task_id = data.get('schedule_task_id')
|
||||
task = None
|
||||
@@ -53,4 +121,4 @@ def run_internal_job(name: str):
|
||||
run.duration_ms = int((run.finished_at - run.started_at).total_seconds() * 1000)
|
||||
run.step_logs = step_logs if step_logs else None
|
||||
db.session.commit()
|
||||
return jsonify({'summary': {'total_count': total_count, 'success_count': success_count, 'failed_count': failed_count, 'skipped_count': skipped_count}, 'details': details, 'errors': errors, 'step_logs': step_logs})
|
||||
return jsonify({'summary': {'total_count': total_count, 'success_count': success_count, 'failed_count': failed_count, 'skipped_count': skipped_count}, 'details': details, 'errors': errors, 'step_logs': step_logs})
|
||||
@@ -334,11 +334,14 @@ def post_schedule():
|
||||
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
|
||||
task.platform_api_path = f'/{task.id}'
|
||||
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:
|
||||
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()
|
||||
|
||||
@@ -257,6 +257,29 @@ class Config:
|
||||
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')
|
||||
@@ -283,6 +306,8 @@ class TestingConfig(Config):
|
||||
WTF_CSRF_ENABLED = False
|
||||
SQLALCHEMY_ENGINE_OPTIONS = {}
|
||||
SCHEDULE_WORKER_ENABLED = False
|
||||
FIXED_ASSETS_SYNC_ENABLED = False
|
||||
FIXED_ASSETS_EXPORT_TO_DOCS = False
|
||||
|
||||
|
||||
config = {
|
||||
|
||||
@@ -291,7 +291,11 @@ class QuickQuestion(Base):
|
||||
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)
|
||||
|
||||
@@ -8,6 +8,7 @@ It is responsible for:
|
||||
1) Forwarding chat requests from this system to Dify in streaming mode.
|
||||
2) Relaying Dify SSE events to the frontend.
|
||||
3) Aggregating answer text and metadata (retriever resources / attribution).
|
||||
Chatflow 模式下来源在 knowledge-retrieval 的 node_finished.outputs.result。
|
||||
4) Enriching retriever resources with original source-file download URLs via
|
||||
the integration API mapping (dataset_id + remote_document_id).
|
||||
5) Persisting chat logs to the local database.
|
||||
@@ -623,7 +624,9 @@ class DifyService:
|
||||
|
||||
app_obj = current_app._get_current_object() if current_app else None
|
||||
persist_data = json.loads(json.dumps(data, ensure_ascii=False, default=str))
|
||||
resources_snapshot = json.loads(json.dumps(retriever_resources, ensure_ascii=False, default=str))
|
||||
# 优先使用已 enrich 并挂到 event 上的 retriever_resources(与 SSE 下发一致)
|
||||
resources_for_persist = data.get('retriever_resources') or retriever_resources
|
||||
resources_snapshot = json.loads(json.dumps(resources_for_persist, ensure_ascii=False, default=str))
|
||||
attribution_snapshot = list(attribution_parts)
|
||||
answer_snapshot = build_final_answer_text(persist_data, event_name)
|
||||
latency_snapshot = int((time.time() - start_time) * 1000)
|
||||
@@ -742,7 +745,11 @@ class DifyService:
|
||||
data.get('conversation_id') or normalized_conversation_id,
|
||||
)
|
||||
|
||||
if event == 'message':
|
||||
if event == 'node_finished':
|
||||
# [STEP] Chatflow 知识检索结果在 node_finished.outputs.result,不在 message_end
|
||||
DifyService._collect_knowledge_retrieval_from_node(retriever_resources, data)
|
||||
|
||||
elif event == 'message':
|
||||
message_count += 1
|
||||
if data.get('answer'):
|
||||
has_sent_answer = True
|
||||
@@ -770,6 +777,7 @@ class DifyService:
|
||||
data['replace_answer'] = True
|
||||
|
||||
if event in ('message_end', 'workflow_finished'):
|
||||
DifyService._attach_retriever_resources_to_event(data, retriever_resources)
|
||||
persist_stream_chat(data, event)
|
||||
if chat_perf_enabled():
|
||||
perf_summary = perf.log_summary(current_app.logger if current_app else None)
|
||||
@@ -1116,6 +1124,77 @@ class DifyService:
|
||||
DifyService._merge_attribution_parts(attribution_parts, event_data.get('citation'))
|
||||
DifyService._merge_attribution_parts(attribution_parts, metadata.get('citation'))
|
||||
|
||||
@staticmethod
|
||||
def _normalize_knowledge_retrieval_result(item: Any) -> dict | None:
|
||||
"""
|
||||
将 Chatflow 知识检索节点的单条 result 规范化为 retriever_resource 结构。
|
||||
核心逻辑:合并 metadata 中的 dataset/document/segment 字段到顶层,供前后端统一解析。
|
||||
"""
|
||||
if not isinstance(item, dict):
|
||||
return None
|
||||
|
||||
metadata = item.get('metadata') if isinstance(item.get('metadata'), dict) else {}
|
||||
document_name = (
|
||||
item.get('document_name')
|
||||
or metadata.get('document_name')
|
||||
or item.get('title')
|
||||
or metadata.get('title')
|
||||
)
|
||||
resource = {
|
||||
**item,
|
||||
'document_name': document_name,
|
||||
'content': item.get('content') or metadata.get('content') or '',
|
||||
'metadata': dict(metadata),
|
||||
}
|
||||
for key in ('dataset_id', 'dataset_name', 'document_id', 'segment_id', 'score'):
|
||||
value = metadata.get(key) if metadata.get(key) not in (None, '') else item.get(key)
|
||||
if value not in (None, '') and resource.get(key) in (None, ''):
|
||||
resource[key] = value
|
||||
return resource
|
||||
|
||||
@staticmethod
|
||||
def _collect_knowledge_retrieval_from_node(retriever_resources: List[Any], event_data: dict):
|
||||
"""
|
||||
从 knowledge-retrieval 节点的 node_finished 事件提取检索来源。
|
||||
核心逻辑:读取 data.outputs.result 列表,规范化后合并进 retriever_resources accumulator。
|
||||
"""
|
||||
if event_data.get('event') != 'node_finished':
|
||||
return
|
||||
|
||||
node = event_data.get('data') if isinstance(event_data.get('data'), dict) else {}
|
||||
if node.get('node_type') != 'knowledge-retrieval':
|
||||
return
|
||||
if node.get('status') not in (None, 'succeeded'):
|
||||
return
|
||||
|
||||
outputs = node.get('outputs') if isinstance(node.get('outputs'), dict) else {}
|
||||
results = outputs.get('result')
|
||||
if not isinstance(results, list):
|
||||
return
|
||||
|
||||
normalized: List[Any] = []
|
||||
for item in results:
|
||||
resource = DifyService._normalize_knowledge_retrieval_result(item)
|
||||
if resource:
|
||||
normalized.append(resource)
|
||||
DifyService._merge_retriever_resources(retriever_resources, normalized)
|
||||
|
||||
@staticmethod
|
||||
def _attach_retriever_resources_to_event(event_data: dict, retriever_resources: List[Any]):
|
||||
"""
|
||||
在 message_end / workflow_finished 下发前,把检索来源挂到 SSE 事件体。
|
||||
核心逻辑:深拷贝 accumulator → enrich 源文件下载链接 → 写入 retriever_resources 与 metadata。
|
||||
"""
|
||||
if not retriever_resources:
|
||||
return
|
||||
|
||||
snapshot = json.loads(json.dumps(retriever_resources, ensure_ascii=False, default=str))
|
||||
DifyService._enrich_retriever_resources_with_source_urls(snapshot)
|
||||
event_data['retriever_resources'] = snapshot
|
||||
metadata = event_data.get('metadata') if isinstance(event_data.get('metadata'), dict) else {}
|
||||
metadata['retriever_resources'] = snapshot
|
||||
event_data['metadata'] = metadata
|
||||
|
||||
@staticmethod
|
||||
def _extract_dify_ids(resource: dict):
|
||||
"""
|
||||
|
||||
@@ -82,6 +82,7 @@ class FaqCacheService:
|
||||
QuickQuestion.is_enabled.is_(True),
|
||||
QuickQuestion.answer.isnot(None),
|
||||
QuickQuestion.answer != "",
|
||||
QuickQuestion.stale_at.is_(None),
|
||||
)
|
||||
.order_by(QuickQuestion.sort_order.asc(), QuickQuestion.id.asc())
|
||||
.all()
|
||||
|
||||
@@ -0,0 +1,224 @@
|
||||
"""
|
||||
backend/app/services/faq_kb_invalidation.py
|
||||
|
||||
用途:知识库文档更新/删除时,标记关联 FAQ 为待复审并暂停 L1 缓存命中。
|
||||
依赖:models.QuickQuestion、KbDifySyncRecord、DifyService._extract_dify_ids、IntegrationApiService。
|
||||
逻辑:dify_sync_service 同步成功后调用 invalidate_faqs_for_kb_document;晋升 FAQ 时写入 source_kb_document_ids。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any, Optional
|
||||
|
||||
from flask import current_app
|
||||
|
||||
from app.models import KbDifySyncRecord, QuickQuestion, db
|
||||
from app.services.dify import DifyService
|
||||
from app.services.integration_api import IntegrationApiService
|
||||
|
||||
STALE_REASON_KB_UPDATED = 'kb_document_updated'
|
||||
STALE_REASON_KB_DELETED = 'kb_document_deleted'
|
||||
|
||||
|
||||
def extract_dify_id_pairs(retriever_resources: list | None) -> list[tuple[str, str]]:
|
||||
"""
|
||||
从 retriever_resources 提取 (dataset_id, remote_document_id) 对。
|
||||
@param retriever_resources - ChatLog / FAQ 上的引用元数据
|
||||
@returns 去重后的 Dify ID 对列表
|
||||
"""
|
||||
if not isinstance(retriever_resources, list):
|
||||
return []
|
||||
pairs: list[tuple[str, str]] = []
|
||||
seen: set[tuple[str, str]] = set()
|
||||
for item in retriever_resources:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
dataset_id, remote_document_id = DifyService._extract_dify_ids(item)
|
||||
if not dataset_id or not remote_document_id:
|
||||
continue
|
||||
key = (str(dataset_id), str(remote_document_id))
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
pairs.append(key)
|
||||
return pairs
|
||||
|
||||
|
||||
def resolve_kb_document_ids_from_resources(retriever_resources: list | None) -> list[int]:
|
||||
"""
|
||||
将 retriever_resources 解析为本地 kb_documents.id 列表。
|
||||
核心逻辑:优先 IntegrationApiService 本地映射,失败则查 KbDifySyncRecord。
|
||||
@param retriever_resources - Dify 检索引用列表
|
||||
@returns 去重后的文档主键列表
|
||||
"""
|
||||
doc_ids: list[int] = []
|
||||
seen: set[int] = set()
|
||||
for dataset_id, remote_document_id in extract_dify_id_pairs(retriever_resources):
|
||||
local_doc_id: Optional[int] = None
|
||||
try:
|
||||
payload = IntegrationApiService._lookup_local_db(dataset_id, remote_document_id)
|
||||
if payload and payload.get('document_id') is not None:
|
||||
local_doc_id = int(payload['document_id'])
|
||||
except Exception:
|
||||
local_doc_id = None
|
||||
if local_doc_id is None:
|
||||
record = (
|
||||
db.session.query(KbDifySyncRecord.document_id)
|
||||
.filter(
|
||||
KbDifySyncRecord.dataset_id == str(dataset_id),
|
||||
KbDifySyncRecord.remote_document_id == str(remote_document_id),
|
||||
)
|
||||
.order_by(KbDifySyncRecord.updated_at.desc(), KbDifySyncRecord.id.desc())
|
||||
.first()
|
||||
)
|
||||
if record and record[0] is not None:
|
||||
local_doc_id = int(record[0])
|
||||
if local_doc_id is not None and local_doc_id not in seen:
|
||||
seen.add(local_doc_id)
|
||||
doc_ids.append(local_doc_id)
|
||||
return doc_ids
|
||||
|
||||
|
||||
def merge_source_kb_document_ids(
|
||||
existing: list | None,
|
||||
retriever_resources: list | None,
|
||||
) -> list[int] | None:
|
||||
"""
|
||||
合并已有 source_kb_document_ids 与 retriever_resources 解析结果。
|
||||
@returns 合并去重后的 ID 列表;无有效 ID 时返回 None
|
||||
"""
|
||||
merged: list[int] = []
|
||||
seen: set[int] = set()
|
||||
for raw in (existing if isinstance(existing, list) else []):
|
||||
try:
|
||||
doc_id = int(raw)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if doc_id not in seen:
|
||||
seen.add(doc_id)
|
||||
merged.append(doc_id)
|
||||
for doc_id in resolve_kb_document_ids_from_resources(retriever_resources):
|
||||
if doc_id not in seen:
|
||||
seen.add(doc_id)
|
||||
merged.append(doc_id)
|
||||
return merged or None
|
||||
|
||||
|
||||
def _faq_links_kb_document(
|
||||
qq: QuickQuestion,
|
||||
document_id: int,
|
||||
dataset_id: str | None,
|
||||
remote_document_id: str | None,
|
||||
) -> bool:
|
||||
"""判断 FAQ 是否关联指定 KB 文档(本地 ID 或 Dify ID 对)。"""
|
||||
source_ids = qq.source_kb_document_ids if isinstance(qq.source_kb_document_ids, list) else []
|
||||
for raw in source_ids:
|
||||
try:
|
||||
if int(raw) == int(document_id):
|
||||
return True
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if not dataset_id or not remote_document_id:
|
||||
return False
|
||||
target = (str(dataset_id), str(remote_document_id))
|
||||
return target in extract_dify_id_pairs(
|
||||
qq.retriever_resources if isinstance(qq.retriever_resources, list) else None
|
||||
)
|
||||
|
||||
|
||||
def find_linked_faqs(
|
||||
document_id: int,
|
||||
*,
|
||||
dataset_id: str | None = None,
|
||||
remote_document_id: str | None = None,
|
||||
cache_enabled_only: bool = True,
|
||||
) -> list[QuickQuestion]:
|
||||
"""
|
||||
查找与 KB 文档关联的全局 FAQ。
|
||||
@param cache_enabled_only - True 时仅扫描 cache_enabled 条目
|
||||
@returns 匹配的 QuickQuestion 列表
|
||||
"""
|
||||
query = db.session.query(QuickQuestion).filter(QuickQuestion.user_id.is_(None))
|
||||
if cache_enabled_only:
|
||||
query = query.filter(QuickQuestion.cache_enabled.is_(True))
|
||||
rows = query.all()
|
||||
return [
|
||||
row
|
||||
for row in rows
|
||||
if _faq_links_kb_document(row, document_id, dataset_id, remote_document_id)
|
||||
]
|
||||
|
||||
|
||||
def mark_faq_stale(qq: QuickQuestion, *, document_id: int, reason: str) -> None:
|
||||
"""
|
||||
将 FAQ 标记为待复审并暂停缓存。
|
||||
核心逻辑:写 stale_* 字段,cache_enabled=false,用户提问将回退 Dify。
|
||||
"""
|
||||
now = datetime.utcnow()
|
||||
qq.stale_at = now
|
||||
qq.stale_reason = reason
|
||||
qq.stale_kb_document_id = document_id
|
||||
qq.cache_enabled = False
|
||||
qq.updated_at = now
|
||||
|
||||
|
||||
def clear_faq_stale(qq: QuickQuestion) -> None:
|
||||
"""清除 FAQ 待复审标记。"""
|
||||
qq.stale_at = None
|
||||
qq.stale_reason = None
|
||||
qq.stale_kb_document_id = None
|
||||
|
||||
|
||||
def invalidate_faqs_for_kb_document(
|
||||
document_id: int,
|
||||
*,
|
||||
reason: str,
|
||||
dataset_id: str | None = None,
|
||||
remote_document_id: str | None = None,
|
||||
) -> int:
|
||||
"""
|
||||
KB 文档变更后,标记所有关联 FAQ 为待复审。
|
||||
@param document_id - kb_documents.id
|
||||
@param reason - stale_reason 枚举值
|
||||
@param dataset_id - 可选,Dify dataset_id
|
||||
@param remote_document_id - 可选,Dify remote document id
|
||||
@returns 标记条数
|
||||
"""
|
||||
if not document_id:
|
||||
return 0
|
||||
try:
|
||||
linked = find_linked_faqs(
|
||||
int(document_id),
|
||||
dataset_id=dataset_id,
|
||||
remote_document_id=remote_document_id,
|
||||
cache_enabled_only=True,
|
||||
)
|
||||
if not linked:
|
||||
return 0
|
||||
for qq in linked:
|
||||
mark_faq_stale(qq, document_id=int(document_id), reason=reason)
|
||||
db.session.commit()
|
||||
return len(linked)
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
if current_app:
|
||||
current_app.logger.warning(
|
||||
'[faq-kb-invalidation] invalidate failed document_id=%s: %s',
|
||||
document_id,
|
||||
exc,
|
||||
)
|
||||
return 0
|
||||
|
||||
|
||||
def apply_retriever_resources_to_faq(qq: QuickQuestion, retriever_resources: Any) -> None:
|
||||
"""
|
||||
将 retriever_resources 写入 FAQ,并解析 source_kb_document_ids。
|
||||
@param qq - QuickQuestion 实例
|
||||
@param retriever_resources - 引用列表或 None
|
||||
"""
|
||||
if isinstance(retriever_resources, list) and retriever_resources:
|
||||
qq.retriever_resources = retriever_resources
|
||||
qq.source_kb_document_ids = merge_source_kb_document_ids(
|
||||
qq.source_kb_document_ids if isinstance(qq.source_kb_document_ids, list) else None,
|
||||
qq.retriever_resources if isinstance(qq.retriever_resources, list) else None,
|
||||
)
|
||||
@@ -0,0 +1,863 @@
|
||||
"""
|
||||
backend/app/services/fixed_assets_snapshot.py
|
||||
|
||||
用途:提供固定资产快照同步、本地结构化落地、Excel 导出与本地查询能力。
|
||||
依赖:Flask current_app、openpyxl、sqlite3、Text2SQLService(延迟导入)、ERP Oracle。
|
||||
逻辑关系:该服务负责将 ERP 固资实时查询能力沉淀为本地快照,供 text2sql 在固资场景下优先查询。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import sqlite3
|
||||
import threading
|
||||
import time
|
||||
from datetime import datetime, timedelta
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from flask import current_app, has_app_context
|
||||
from openpyxl import Workbook
|
||||
|
||||
from app.path_utils import backend_dir
|
||||
|
||||
_worker_started = False
|
||||
_worker_lock = threading.Lock()
|
||||
_sync_lock = threading.Lock()
|
||||
|
||||
|
||||
class FixedAssetsSnapshotService:
|
||||
"""固定资产快照同步与本地查询服务。"""
|
||||
|
||||
SNAPSHOT_SQL_MARKER = "SNAPSHOT://FIXED_ASSETS"
|
||||
SNAPSHOT_KIND = "fixed_assets_snapshot_preview"
|
||||
|
||||
VISIBLE_COLUMNS = (
|
||||
"资产编号",
|
||||
"资产名称",
|
||||
"规格型号",
|
||||
"保管人姓名",
|
||||
"保管部门名称",
|
||||
"存放位置名称",
|
||||
"资产状态",
|
||||
"预留残值",
|
||||
"供应厂商",
|
||||
"资产性质",
|
||||
"本币单价",
|
||||
"数量",
|
||||
"计量单位",
|
||||
"取得日期",
|
||||
"入账日期",
|
||||
)
|
||||
|
||||
NATURE_MAP = {
|
||||
"1": "有形资产",
|
||||
"2": "无形资产",
|
||||
"3": "土地",
|
||||
"4": "递耗资产",
|
||||
"5": "费用",
|
||||
}
|
||||
STATUS_MAP = {
|
||||
"0": "取得",
|
||||
"1": "资本化",
|
||||
"2": "折旧中",
|
||||
"3": "外送",
|
||||
"4": "折毕",
|
||||
"5": "出售",
|
||||
"6": "销账",
|
||||
"7": "折旧再提",
|
||||
"8": "改良",
|
||||
"9": "重估",
|
||||
"X": "被资本",
|
||||
"Z": "停用",
|
||||
}
|
||||
STOPWORDS_PATTERN = re.compile(
|
||||
r"(固定资产|固资|资产编号|财产编号|资产编码|编号|资产名称|设备名称|资产|设备|请问|帮我|看下|查下|查询|统计|核对|看看|我想知道|有多少台?|有多少|多少台?|多少|明细|列表|数据|结果|并且|以及|还有|和|按|根据|生成图表|生成excel|生成表单|导出excel|导出表单|导出)",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def _storage_root(cls) -> Path:
|
||||
path_value = current_app.config.get("FIXED_ASSETS_STORAGE_ROOT")
|
||||
return Path(str(path_value)).resolve()
|
||||
|
||||
@classmethod
|
||||
def _docs_export_root(cls) -> Path:
|
||||
path_value = current_app.config.get("FIXED_ASSETS_DOCS_EXPORT_ROOT")
|
||||
return Path(str(path_value)).resolve()
|
||||
|
||||
@classmethod
|
||||
def _snapshots_dir(cls) -> Path:
|
||||
return cls._storage_root() / "snapshots"
|
||||
|
||||
@classmethod
|
||||
def _latest_dir(cls) -> Path:
|
||||
return cls._storage_root() / "latest"
|
||||
|
||||
@classmethod
|
||||
def _manifest_path(cls) -> Path:
|
||||
return cls._storage_root() / "manifest.json"
|
||||
|
||||
@classmethod
|
||||
def _ensure_storage_dirs(cls) -> None:
|
||||
for path in (cls._storage_root(), cls._snapshots_dir(), cls._latest_dir()):
|
||||
path.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
@classmethod
|
||||
def _latest_db_path(cls) -> Path:
|
||||
return cls._latest_dir() / "FixedAssets_latest.db"
|
||||
|
||||
@classmethod
|
||||
def _latest_xlsx_path(cls) -> Path:
|
||||
return cls._latest_dir() / "FixedAssets_latest.xlsx"
|
||||
|
||||
@staticmethod
|
||||
def _stringify(value: Any) -> str:
|
||||
if value is None:
|
||||
return ""
|
||||
return str(value).strip()
|
||||
|
||||
@classmethod
|
||||
def _normalize_search_text(cls, text: str) -> str:
|
||||
cleaned = str(text or "").upper()
|
||||
cleaned = re.sub(r"[\s\-_|,::;;,。()()/\\]+", "", cleaned)
|
||||
return cleaned
|
||||
|
||||
@classmethod
|
||||
def _build_remark(cls, row: dict[str, str]) -> str:
|
||||
parts = [
|
||||
f"资产编号:{row.get('资产编号', '')}",
|
||||
f"资产名称:{row.get('资产名称', '')}",
|
||||
f"规格型号:{row.get('规格型号', '')}",
|
||||
f"保管人姓名:{row.get('保管人姓名', '')}",
|
||||
f"保管部门名称:{row.get('保管部门名称', '')}",
|
||||
f"存放位置名称:{row.get('存放位置名称', '')}",
|
||||
f"资产状态:{row.get('资产状态', '')}",
|
||||
f"供应厂商:{row.get('供应厂商', '')}",
|
||||
f"资产性质:{row.get('资产性质', '')}",
|
||||
]
|
||||
return " | ".join(parts)
|
||||
|
||||
@classmethod
|
||||
def _snapshot_identity_key(cls, row: dict[str, str], fallback_index: int) -> str:
|
||||
"""生成快照去重键,优先使用资产编号。"""
|
||||
asset_no = cls._stringify(row.get("资产编号"))
|
||||
if asset_no:
|
||||
return asset_no.upper()
|
||||
return f"__ROW_{fallback_index}"
|
||||
|
||||
@classmethod
|
||||
def _snapshot_row_score(cls, row: dict[str, str]) -> tuple[int, int]:
|
||||
"""为重复资产选择信息更完整的一条记录。"""
|
||||
preferred_fields = (
|
||||
"资产名称",
|
||||
"规格型号",
|
||||
"保管人姓名",
|
||||
"保管部门名称",
|
||||
"存放位置名称",
|
||||
"资产状态",
|
||||
"供应厂商",
|
||||
"资产性质",
|
||||
"本币单价",
|
||||
"数量",
|
||||
"计量单位",
|
||||
"取得日期",
|
||||
"入账日期",
|
||||
)
|
||||
filled_count = sum(1 for key in preferred_fields if cls._stringify(row.get(key)))
|
||||
text_length = sum(len(cls._stringify(row.get(key))) for key in preferred_fields)
|
||||
return filled_count, text_length
|
||||
|
||||
@classmethod
|
||||
def _dedupe_snapshot_rows(cls, rows: list[dict[str, str]]) -> list[dict[str, str]]:
|
||||
"""按资产编号对快照结果去重,避免联表重复导致同一资产多次入库。"""
|
||||
deduped: dict[str, dict[str, str]] = {}
|
||||
for index, row in enumerate(rows):
|
||||
dedupe_key = cls._snapshot_identity_key(row, index)
|
||||
existing = deduped.get(dedupe_key)
|
||||
if existing is None:
|
||||
deduped[dedupe_key] = row
|
||||
continue
|
||||
if cls._snapshot_row_score(row) > cls._snapshot_row_score(existing):
|
||||
deduped[dedupe_key] = row
|
||||
return list(deduped.values())
|
||||
|
||||
@classmethod
|
||||
def _snapshot_sql(cls) -> str:
|
||||
return """
|
||||
SELECT DISTINCT
|
||||
faj.faj02 AS "资产编号",
|
||||
faj.faj06 AS "资产名称",
|
||||
faj.faj061 AS "资产名称2",
|
||||
faj.faj08 AS "规格型号",
|
||||
gen.gen01 AS "保管人工号",
|
||||
gen.gen02 AS "保管人姓名",
|
||||
gem.gem01 AS "保管部门编号",
|
||||
gem.gem02 AS "保管部门名称",
|
||||
faf.faf02 AS "存放位置名称",
|
||||
faj.faj43 AS "资产状态代码",
|
||||
faj.faj31 AS "预留残值",
|
||||
pmc.pmc03 AS "供应厂商",
|
||||
faj.faj09 AS "资产性质代码",
|
||||
faj.faj13 AS "本币单价",
|
||||
faj.faj17 AS "数量",
|
||||
faj.faj18 AS "计量单位",
|
||||
TO_CHAR(faj.faj25, 'YYYY-MM-DD HH24:MI:SS') AS "取得日期",
|
||||
TO_CHAR(faj.faj26, 'YYYY-MM-DD HH24:MI:SS') AS "入账日期",
|
||||
TRIM(NVL(faj.faj22, '')) AS "营运中心代码",
|
||||
TRIM(NVL(faj.site, '')) AS "站点代码"
|
||||
FROM ERP_VIEW_USER.ERP_FAJ_FILE_V faj
|
||||
LEFT JOIN ERP_VIEW_USER.ERP_GEN_FILE_V gen
|
||||
ON gen.gen01 = faj.faj19
|
||||
AND gen.site = faj.site
|
||||
LEFT JOIN ERP_VIEW_USER.ERP_GEM_FILE_V gem
|
||||
ON gem.gem01 = faj.faj20
|
||||
AND gem.site = faj.site
|
||||
LEFT JOIN ERP_VIEW_USER.ERP_FAF_FILE_V faf
|
||||
ON faf.faf01 = faj.faj21
|
||||
AND faf.site = faj.site
|
||||
LEFT JOIN ERP_VIEW_USER.ERP_PMC_FILE_V pmc
|
||||
ON pmc.pmc01 = faj.faj10
|
||||
AND pmc.site = faj.site
|
||||
WHERE UPPER(TRIM(NVL(faj.faj22, ''))) IN ('HXJM', 'HTT', 'HTE')
|
||||
ORDER BY faj.faj02
|
||||
""".strip()
|
||||
|
||||
@classmethod
|
||||
def _oracle_credentials(cls) -> tuple[str, str, str]:
|
||||
username = str(current_app.config.get("FIXED_ASSETS_ERP_USERNAME") or "EXT_VIEW_USER").strip()
|
||||
password = str(current_app.config.get("FIXED_ASSETS_ERP_PASSWORD") or "extviewuser").strip()
|
||||
dsn = str(current_app.config.get("FIXED_ASSETS_ERP_DSN") or os.getenv("ERP_DB_DSN") or "192.168.8.24:1521/topprod").strip()
|
||||
return username, password, dsn
|
||||
|
||||
@classmethod
|
||||
def _fetch_snapshot_rows(cls, timeout_seconds: int) -> list[dict[str, str]]:
|
||||
"""从 ERP Oracle 拉取固定资产全量快照。"""
|
||||
import oracledb
|
||||
from app.services.text2sql import Text2SQLService
|
||||
|
||||
username, password, dsn = cls._oracle_credentials()
|
||||
Text2SQLService._init_oracle_client(oracledb)
|
||||
|
||||
connection = None
|
||||
cursor = None
|
||||
try:
|
||||
connection = oracledb.connect(user=username, password=password, dsn=dsn)
|
||||
connection.call_timeout = max(1, int(timeout_seconds)) * 1000
|
||||
cursor = connection.cursor()
|
||||
cursor.execute(cls._snapshot_sql())
|
||||
columns = [str(col[0] or "").strip() for col in cursor.description]
|
||||
rows = cursor.fetchall()
|
||||
normalized_rows: list[dict[str, str]] = []
|
||||
for raw_row in rows:
|
||||
item = {
|
||||
columns[idx]: cls._stringify(value)
|
||||
for idx, value in enumerate(raw_row)
|
||||
}
|
||||
item["资产状态"] = cls.STATUS_MAP.get(item.get("资产状态代码", "").upper(), item.get("资产状态代码", ""))
|
||||
item["资产性质"] = cls.NATURE_MAP.get(item.get("资产性质代码", ""), item.get("资产性质代码", ""))
|
||||
item["备注"] = cls._build_remark(item)
|
||||
item["备注标准化"] = cls._normalize_search_text(item["备注"])
|
||||
normalized_rows.append(item)
|
||||
return cls._dedupe_snapshot_rows(normalized_rows)
|
||||
finally:
|
||||
if cursor is not None:
|
||||
try:
|
||||
cursor.close()
|
||||
except Exception:
|
||||
pass
|
||||
if connection is not None:
|
||||
try:
|
||||
connection.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@classmethod
|
||||
def _snapshot_db_schema_sql(cls) -> list[str]:
|
||||
return [
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS fixed_assets (
|
||||
asset_no TEXT,
|
||||
asset_name TEXT,
|
||||
asset_name2 TEXT,
|
||||
specification TEXT,
|
||||
custodian_id TEXT,
|
||||
custodian_name TEXT,
|
||||
department_code TEXT,
|
||||
department_name TEXT,
|
||||
location_name TEXT,
|
||||
asset_status TEXT,
|
||||
asset_status_code TEXT,
|
||||
residual_value TEXT,
|
||||
vendor_name TEXT,
|
||||
asset_nature TEXT,
|
||||
asset_nature_code TEXT,
|
||||
unit_price TEXT,
|
||||
quantity TEXT,
|
||||
unit TEXT,
|
||||
acquisition_date TEXT,
|
||||
accounting_date TEXT,
|
||||
operating_center_code TEXT,
|
||||
site_code TEXT,
|
||||
remark TEXT,
|
||||
remark_normalized TEXT,
|
||||
snapshot_version TEXT,
|
||||
snapshot_date TEXT
|
||||
)
|
||||
""".strip(),
|
||||
"CREATE INDEX IF NOT EXISTS idx_fixed_assets_no ON fixed_assets(asset_no)",
|
||||
"CREATE INDEX IF NOT EXISTS idx_fixed_assets_name ON fixed_assets(asset_name)",
|
||||
"CREATE INDEX IF NOT EXISTS idx_fixed_assets_name2 ON fixed_assets(asset_name2)",
|
||||
"CREATE INDEX IF NOT EXISTS idx_fixed_assets_spec ON fixed_assets(specification)",
|
||||
"CREATE INDEX IF NOT EXISTS idx_fixed_assets_custodian ON fixed_assets(custodian_name)",
|
||||
"CREATE INDEX IF NOT EXISTS idx_fixed_assets_department ON fixed_assets(department_name)",
|
||||
"CREATE INDEX IF NOT EXISTS idx_fixed_assets_location ON fixed_assets(location_name)",
|
||||
"CREATE INDEX IF NOT EXISTS idx_fixed_assets_status ON fixed_assets(asset_status)",
|
||||
"CREATE INDEX IF NOT EXISTS idx_fixed_assets_vendor ON fixed_assets(vendor_name)",
|
||||
"CREATE INDEX IF NOT EXISTS idx_fixed_assets_nature ON fixed_assets(asset_nature)",
|
||||
"CREATE INDEX IF NOT EXISTS idx_fixed_assets_remark_norm ON fixed_assets(remark_normalized)",
|
||||
]
|
||||
|
||||
@classmethod
|
||||
def _write_snapshot_db(cls, db_path: Path, rows: list[dict[str, str]], version: str, snapshot_date: str) -> None:
|
||||
"""将快照数据写入 SQLite。"""
|
||||
if db_path.exists():
|
||||
db_path.unlink()
|
||||
conn = sqlite3.connect(db_path)
|
||||
try:
|
||||
cursor = conn.cursor()
|
||||
for statement in cls._snapshot_db_schema_sql():
|
||||
cursor.execute(statement)
|
||||
|
||||
insert_sql = """
|
||||
INSERT INTO fixed_assets (
|
||||
asset_no, asset_name, asset_name2, specification, custodian_id, custodian_name,
|
||||
department_code, department_name, location_name, asset_status, asset_status_code,
|
||||
residual_value, vendor_name, asset_nature, asset_nature_code, unit_price, quantity,
|
||||
unit, acquisition_date, accounting_date, operating_center_code, site_code, remark,
|
||||
remark_normalized, snapshot_version, snapshot_date
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
""".strip()
|
||||
payload = []
|
||||
for item in rows:
|
||||
payload.append(
|
||||
(
|
||||
item.get("资产编号", ""),
|
||||
item.get("资产名称", ""),
|
||||
item.get("资产名称2", ""),
|
||||
item.get("规格型号", ""),
|
||||
item.get("保管人工号", ""),
|
||||
item.get("保管人姓名", ""),
|
||||
item.get("保管部门编号", ""),
|
||||
item.get("保管部门名称", ""),
|
||||
item.get("存放位置名称", ""),
|
||||
item.get("资产状态", ""),
|
||||
item.get("资产状态代码", ""),
|
||||
item.get("预留残值", ""),
|
||||
item.get("供应厂商", ""),
|
||||
item.get("资产性质", ""),
|
||||
item.get("资产性质代码", ""),
|
||||
item.get("本币单价", ""),
|
||||
item.get("数量", ""),
|
||||
item.get("计量单位", ""),
|
||||
item.get("取得日期", ""),
|
||||
item.get("入账日期", ""),
|
||||
item.get("营运中心代码", ""),
|
||||
item.get("站点代码", ""),
|
||||
item.get("备注", ""),
|
||||
item.get("备注标准化", ""),
|
||||
version,
|
||||
snapshot_date,
|
||||
)
|
||||
)
|
||||
cursor.executemany(insert_sql, payload)
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
@classmethod
|
||||
def _export_snapshot_excel(cls, excel_path: Path, rows: list[dict[str, str]]) -> None:
|
||||
"""导出快照 Excel 文件。"""
|
||||
workbook = Workbook()
|
||||
sheet = workbook.active
|
||||
sheet.title = "FixedAssets"
|
||||
header = list(cls.VISIBLE_COLUMNS) + ["备注"]
|
||||
sheet.append(header)
|
||||
for item in rows:
|
||||
sheet.append([
|
||||
item.get("资产编号", ""),
|
||||
item.get("资产名称", ""),
|
||||
item.get("规格型号", ""),
|
||||
item.get("保管人姓名", ""),
|
||||
item.get("保管部门名称", ""),
|
||||
item.get("存放位置名称", ""),
|
||||
item.get("资产状态", ""),
|
||||
item.get("预留残值", ""),
|
||||
item.get("供应厂商", ""),
|
||||
item.get("资产性质", ""),
|
||||
item.get("本币单价", ""),
|
||||
item.get("数量", ""),
|
||||
item.get("计量单位", ""),
|
||||
item.get("取得日期", ""),
|
||||
item.get("入账日期", ""),
|
||||
item.get("备注", ""),
|
||||
])
|
||||
workbook.save(excel_path)
|
||||
|
||||
@classmethod
|
||||
def _write_manifest(cls, payload: dict[str, Any]) -> None:
|
||||
cls._ensure_storage_dirs()
|
||||
cls._manifest_path().write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
|
||||
@classmethod
|
||||
def _load_manifest(cls) -> dict[str, Any]:
|
||||
path = cls._manifest_path()
|
||||
if not path.exists():
|
||||
return {}
|
||||
try:
|
||||
return json.loads(path.read_text(encoding="utf-8"))
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
@classmethod
|
||||
def _promote_snapshot(cls, version: str, db_path: Path, excel_path: Path) -> dict[str, str]:
|
||||
cls._ensure_storage_dirs()
|
||||
latest_db = cls._latest_db_path()
|
||||
latest_xlsx = cls._latest_xlsx_path()
|
||||
shutil.copy2(db_path, latest_db)
|
||||
shutil.copy2(excel_path, latest_xlsx)
|
||||
|
||||
docs_exports: dict[str, str] = {}
|
||||
if current_app.config.get("FIXED_ASSETS_EXPORT_TO_DOCS", True):
|
||||
docs_root = cls._docs_export_root()
|
||||
docs_root.mkdir(parents=True, exist_ok=True)
|
||||
docs_latest = docs_root / "FixedAssets_latest.xlsx"
|
||||
docs_versioned = docs_root / f"FixedAssets_{version}.xlsx"
|
||||
shutil.copy2(excel_path, docs_latest)
|
||||
shutil.copy2(excel_path, docs_versioned)
|
||||
docs_exports = {
|
||||
"docs_latest_xlsx": str(docs_latest),
|
||||
"docs_versioned_xlsx": str(docs_versioned),
|
||||
}
|
||||
return {
|
||||
"latest_db": str(latest_db),
|
||||
"latest_xlsx": str(latest_xlsx),
|
||||
**docs_exports,
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def _cleanup_temp_snapshot_files(cls, directory: Path) -> None:
|
||||
"""清理 Excel 打开时遗留的临时锁文件。"""
|
||||
if not directory.exists():
|
||||
return
|
||||
for temp_file in directory.glob("~$FixedAssets*.xlsx"):
|
||||
try:
|
||||
temp_file.unlink()
|
||||
except OSError as exc:
|
||||
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)
|
||||
|
||||
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):
|
||||
if file_path.name.startswith("~$"):
|
||||
continue
|
||||
version_key = file_path.stem
|
||||
version_files.setdefault(version_key, []).append(file_path)
|
||||
|
||||
version_keys = sorted(version_files.keys(), reverse=True)
|
||||
obsolete_keys = version_keys[safe_keep_count:]
|
||||
for version_key in obsolete_keys:
|
||||
for file_path in version_files.get(version_key, []):
|
||||
try:
|
||||
file_path.unlink()
|
||||
except OSError as exc:
|
||||
cls._log("warning", f"Failed to remove obsolete snapshot file {file_path}: {exc}")
|
||||
|
||||
@classmethod
|
||||
def is_snapshot_available(cls) -> bool:
|
||||
return cls._latest_db_path().exists()
|
||||
|
||||
@classmethod
|
||||
def sync_once(cls, *, reason: str = "manual", attempt: int = 1) -> dict[str, Any]:
|
||||
"""执行一次固资快照同步。"""
|
||||
with _sync_lock:
|
||||
cls._ensure_storage_dirs()
|
||||
timeout_seconds = int(current_app.config.get("FIXED_ASSETS_SYNC_TIMEOUT_SECONDS", 600) or 600)
|
||||
started_at = datetime.utcnow()
|
||||
version = started_at.strftime("%Y%m%d_%H%M%S")
|
||||
snapshot_date = started_at.strftime("%Y-%m-%d")
|
||||
version_db = cls._snapshots_dir() / f"FixedAssets_{version}.db"
|
||||
version_xlsx = cls._snapshots_dir() / f"FixedAssets_{version}.xlsx"
|
||||
|
||||
try:
|
||||
rows = cls._fetch_snapshot_rows(timeout_seconds)
|
||||
cls._write_snapshot_db(version_db, rows, version, snapshot_date)
|
||||
cls._export_snapshot_excel(version_xlsx, rows)
|
||||
promoted_paths = cls._promote_snapshot(version, version_db, version_xlsx)
|
||||
cls._cleanup_history_snapshots()
|
||||
|
||||
manifest = {
|
||||
"status": "success",
|
||||
"last_reason": reason,
|
||||
"last_attempt": attempt,
|
||||
"last_started_at": started_at.isoformat(),
|
||||
"last_finished_at": datetime.utcnow().isoformat(),
|
||||
"last_success_at": datetime.utcnow().isoformat(),
|
||||
"current_version": version,
|
||||
"snapshot_date": snapshot_date,
|
||||
"row_count": len(rows),
|
||||
"files": {
|
||||
"versioned_db": str(version_db),
|
||||
"versioned_xlsx": str(version_xlsx),
|
||||
**promoted_paths,
|
||||
},
|
||||
}
|
||||
cls._write_manifest(manifest)
|
||||
cls._log("info", f"Fixed assets snapshot synced successfully version={version} row_count={len(rows)}")
|
||||
return manifest
|
||||
except Exception as exc:
|
||||
manifest = cls._load_manifest()
|
||||
manifest.update({
|
||||
"status": "failed",
|
||||
"last_reason": reason,
|
||||
"last_attempt": attempt,
|
||||
"last_started_at": started_at.isoformat(),
|
||||
"last_finished_at": datetime.utcnow().isoformat(),
|
||||
"last_error": str(exc),
|
||||
})
|
||||
cls._write_manifest(manifest)
|
||||
cls._log("warning", f"Fixed assets snapshot sync failed attempt={attempt}: {exc}")
|
||||
raise
|
||||
|
||||
@classmethod
|
||||
def sync_with_retry(cls, *, reason: str = "schedule") -> dict[str, Any]:
|
||||
"""按配置执行同步与重试。"""
|
||||
max_attempts = max(1, int(current_app.config.get("FIXED_ASSETS_SYNC_MAX_ATTEMPTS", 4) or 4))
|
||||
retry_interval_seconds = max(
|
||||
60,
|
||||
int(current_app.config.get("FIXED_ASSETS_SYNC_RETRY_INTERVAL_MINUTES", 30) or 30) * 60,
|
||||
)
|
||||
last_error: Exception | None = None
|
||||
for attempt in range(1, max_attempts + 1):
|
||||
try:
|
||||
return cls.sync_once(reason=reason, attempt=attempt)
|
||||
except Exception as exc: # pragma: no cover - runtime branch
|
||||
last_error = exc
|
||||
if attempt >= max_attempts:
|
||||
break
|
||||
cls._log(
|
||||
"warning",
|
||||
f"Fixed assets snapshot will retry after {retry_interval_seconds}s, attempt={attempt}, error={exc}",
|
||||
)
|
||||
time.sleep(retry_interval_seconds)
|
||||
if last_error is not None:
|
||||
raise last_error
|
||||
raise RuntimeError("Fixed assets snapshot sync failed without explicit error")
|
||||
|
||||
@classmethod
|
||||
def _tokenize_query(cls, query: str) -> list[str]:
|
||||
cleaned = cls.STOPWORDS_PATTERN.sub(" ", str(query or ""))
|
||||
tokens = re.findall(r"[A-Za-z0-9\u4e00-\u9fff()()_-]{2,40}", cleaned)
|
||||
normalized_tokens: list[str] = []
|
||||
for token in tokens:
|
||||
normalized = cls._normalize_search_text(token)
|
||||
if normalized and normalized not in normalized_tokens:
|
||||
normalized_tokens.append(normalized)
|
||||
return normalized_tokens[:5]
|
||||
|
||||
@classmethod
|
||||
def _build_where_clause(cls, query: str, user_context: dict[str, Any] | None = None) -> tuple[str, list[str]]:
|
||||
"""根据用户问句生成本地快照过滤条件。"""
|
||||
from app.services.text2sql import Text2SQLService
|
||||
|
||||
clauses: list[str] = []
|
||||
params: list[str] = []
|
||||
|
||||
advanced_conds = Text2SQLService._extract_advanced_asset_conditions(query)
|
||||
asset_code = advanced_conds.get("asset_code") or Text2SQLService._extract_asset_code(query)
|
||||
asset_name = advanced_conds.get("asset_name") or Text2SQLService._extract_asset_name_keyword(query)
|
||||
asset_nature_code = Text2SQLService._extract_asset_nature_code(query)
|
||||
explicit_scope = Text2SQLService._extract_asset_scope(query)
|
||||
has_explicit_location = bool(advanced_conds.get("location"))
|
||||
has_explicit_vendor = bool(advanced_conds.get("vendor"))
|
||||
has_explicit_spec = bool(advanced_conds.get("spec"))
|
||||
has_explicit_status = bool(advanced_conds.get("status"))
|
||||
has_explicit_person = bool(explicit_scope.get("person"))
|
||||
has_explicit_department = bool(explicit_scope.get("department"))
|
||||
should_use_generic_keyword_search = bool(
|
||||
asset_name
|
||||
and not asset_code
|
||||
and not has_explicit_location
|
||||
and not has_explicit_vendor
|
||||
and not has_explicit_spec
|
||||
and not has_explicit_status
|
||||
and not has_explicit_person
|
||||
and not has_explicit_department
|
||||
and not asset_nature_code
|
||||
)
|
||||
|
||||
if asset_code:
|
||||
clauses.append("UPPER(COALESCE(asset_no, '')) LIKE ?")
|
||||
params.append(f"%{asset_code.upper()}%")
|
||||
if asset_name and not should_use_generic_keyword_search:
|
||||
clauses.append("(UPPER(COALESCE(asset_name, '')) LIKE ? OR UPPER(COALESCE(asset_name2, '')) LIKE ?)")
|
||||
params.extend([f"%{asset_name.upper()}%", f"%{asset_name.upper()}%"])
|
||||
if "spec" in advanced_conds:
|
||||
clauses.append("UPPER(COALESCE(specification, '')) LIKE ?")
|
||||
params.append(f"%{advanced_conds['spec'].upper()}%")
|
||||
if "status" in advanced_conds:
|
||||
clauses.append("UPPER(COALESCE(asset_status, '')) LIKE ?")
|
||||
params.append(f"%{advanced_conds['status'].upper()}%")
|
||||
if "vendor" in advanced_conds:
|
||||
clauses.append("UPPER(COALESCE(vendor_name, '')) LIKE ?")
|
||||
params.append(f"%{advanced_conds['vendor'].upper()}%")
|
||||
if "location" in advanced_conds:
|
||||
clauses.append("UPPER(COALESCE(location_name, '')) LIKE ?")
|
||||
params.append(f"%{advanced_conds['location'].upper()}%")
|
||||
if asset_nature_code:
|
||||
asset_nature = cls.NATURE_MAP.get(asset_nature_code, asset_nature_code)
|
||||
clauses.append("UPPER(COALESCE(asset_nature, '')) = ?")
|
||||
params.append(asset_nature.upper())
|
||||
|
||||
explicit_person = explicit_scope.get("person")
|
||||
if explicit_person:
|
||||
clauses.append("UPPER(COALESCE(custodian_name, '')) LIKE ?")
|
||||
params.append(f"%{explicit_person.upper()}%")
|
||||
|
||||
explicit_department = explicit_scope.get("department")
|
||||
if explicit_department:
|
||||
clauses.append("UPPER(COALESCE(department_name, '')) LIKE ?")
|
||||
params.append(f"%{explicit_department.upper()}%")
|
||||
|
||||
if should_use_generic_keyword_search:
|
||||
normalized_keyword = cls._normalize_search_text(asset_name)
|
||||
clauses.append(
|
||||
"("
|
||||
"UPPER(COALESCE(asset_name, '')) LIKE ? "
|
||||
"OR UPPER(COALESCE(asset_name2, '')) LIKE ? "
|
||||
"OR UPPER(COALESCE(specification, '')) LIKE ? "
|
||||
"OR UPPER(COALESCE(location_name, '')) LIKE ? "
|
||||
"OR UPPER(COALESCE(custodian_name, '')) LIKE ? "
|
||||
"OR UPPER(COALESCE(department_name, '')) LIKE ? "
|
||||
"OR UPPER(COALESCE(vendor_name, '')) LIKE ? "
|
||||
"OR UPPER(COALESCE(remark_normalized, '')) LIKE ?"
|
||||
")"
|
||||
)
|
||||
params.extend(
|
||||
[
|
||||
f"%{asset_name.upper()}%",
|
||||
f"%{asset_name.upper()}%",
|
||||
f"%{asset_name.upper()}%",
|
||||
f"%{asset_name.upper()}%",
|
||||
f"%{asset_name.upper()}%",
|
||||
f"%{asset_name.upper()}%",
|
||||
f"%{asset_name.upper()}%",
|
||||
f"%{normalized_keyword}%",
|
||||
]
|
||||
)
|
||||
|
||||
normalized_user = user_context or {}
|
||||
if Text2SQLService._is_self_asset_query(query):
|
||||
self_clauses = []
|
||||
for candidate in (normalized_user.get("employee_id"), normalized_user.get("username")):
|
||||
value = cls._stringify(candidate)
|
||||
if not value:
|
||||
continue
|
||||
self_clauses.append("UPPER(COALESCE(custodian_id, '')) = ?")
|
||||
params.append(value.upper())
|
||||
real_name = cls._stringify(normalized_user.get("real_name"))
|
||||
if real_name:
|
||||
self_clauses.append("UPPER(COALESCE(custodian_name, '')) = ?")
|
||||
params.append(real_name.upper())
|
||||
if self_clauses:
|
||||
clauses.append("(" + " OR ".join(self_clauses) + ")")
|
||||
|
||||
if not clauses and not Text2SQLService._is_company_asset_detail_query(query):
|
||||
tokens = cls._tokenize_query(query)
|
||||
for token in tokens:
|
||||
clauses.append("UPPER(COALESCE(remark_normalized, '')) LIKE ?")
|
||||
params.append(f"%{token}%")
|
||||
|
||||
where_sql = " AND ".join(clauses) if clauses else "1=1"
|
||||
return where_sql, params
|
||||
|
||||
@classmethod
|
||||
def query_assets(
|
||||
cls,
|
||||
query: str,
|
||||
*,
|
||||
limit: int = 10,
|
||||
offset: int = 0,
|
||||
user_context: dict[str, Any] | None = None,
|
||||
) -> tuple[list[str], list[tuple], int]:
|
||||
"""查询最新固资快照。"""
|
||||
if not cls.is_snapshot_available():
|
||||
return ["Error"], [("固定资产快照尚未生成,请稍后重试。",)], 0
|
||||
|
||||
where_sql, params = cls._build_where_clause(query, user_context=user_context)
|
||||
deduped_assets_cte = """
|
||||
WITH deduped_assets AS (
|
||||
SELECT *
|
||||
FROM (
|
||||
SELECT
|
||||
fixed_assets.*,
|
||||
ROW_NUMBER() OVER (
|
||||
PARTITION BY CASE
|
||||
WHEN TRIM(COALESCE(asset_no, '')) = '' THEN '__ROW_' || rowid
|
||||
ELSE UPPER(TRIM(asset_no))
|
||||
END
|
||||
ORDER BY rowid
|
||||
) AS dedupe_rn
|
||||
FROM fixed_assets
|
||||
)
|
||||
WHERE dedupe_rn = 1
|
||||
)
|
||||
""".strip()
|
||||
visible_select = """
|
||||
asset_no AS "资产编号",
|
||||
asset_name AS "资产名称",
|
||||
specification AS "规格型号",
|
||||
custodian_name AS "保管人姓名",
|
||||
department_name AS "保管部门名称",
|
||||
location_name AS "存放位置名称",
|
||||
asset_status AS "资产状态",
|
||||
residual_value AS "预留残值",
|
||||
vendor_name AS "供应厂商",
|
||||
asset_nature AS "资产性质",
|
||||
unit_price AS "本币单价",
|
||||
quantity AS "数量",
|
||||
unit AS "计量单位",
|
||||
acquisition_date AS "取得日期",
|
||||
accounting_date AS "入账日期"
|
||||
""".strip()
|
||||
list_sql = f"""
|
||||
{deduped_assets_cte}
|
||||
SELECT {visible_select}
|
||||
FROM deduped_assets
|
||||
WHERE {where_sql}
|
||||
ORDER BY asset_no
|
||||
LIMIT ? OFFSET ?
|
||||
""".strip()
|
||||
count_sql = f"""
|
||||
{deduped_assets_cte}
|
||||
SELECT COUNT(*) FROM deduped_assets WHERE {where_sql}
|
||||
""".strip()
|
||||
|
||||
conn = sqlite3.connect(cls._latest_db_path())
|
||||
try:
|
||||
cursor = conn.cursor()
|
||||
cursor.execute(count_sql, params)
|
||||
total_count = int(cursor.fetchone()[0] or 0)
|
||||
cursor.execute(list_sql, [*params, max(1, int(limit)), max(0, int(offset))])
|
||||
columns = [str(item[0] or "").strip() for item in cursor.description]
|
||||
rows = [tuple(row) for row in cursor.fetchall()]
|
||||
return columns, rows, total_count
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
@classmethod
|
||||
def get_snapshot_preview_payload(
|
||||
cls,
|
||||
query: str,
|
||||
columns: list[str],
|
||||
rows: list[tuple],
|
||||
total_count: int,
|
||||
) -> dict[str, Any]:
|
||||
return {
|
||||
"kind": "text2sql_result_preview",
|
||||
"previewable": total_count > len(rows or []),
|
||||
"query": query,
|
||||
"sql": cls.SNAPSHOT_SQL_MARKER,
|
||||
"total_count": total_count,
|
||||
"preview_row_count": len(rows or []),
|
||||
"display_columns": list(columns or []),
|
||||
"data_source": cls.SNAPSHOT_KIND,
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def is_snapshot_sql(cls, sql: str) -> bool:
|
||||
return str(sql or "").strip().startswith(cls.SNAPSHOT_SQL_MARKER)
|
||||
|
||||
@classmethod
|
||||
def snapshot_sql_label(cls) -> str:
|
||||
manifest = cls._load_manifest()
|
||||
version = str(manifest.get("current_version") or "").strip()
|
||||
if version:
|
||||
return f"固定资产快照查询(版本 {version})"
|
||||
return "固定资产快照查询"
|
||||
|
||||
@classmethod
|
||||
def _should_run_bootstrap(cls) -> bool:
|
||||
return bool(current_app.config.get("FIXED_ASSETS_SYNC_ON_BOOT_IF_MISSING", True)) and not cls.is_snapshot_available()
|
||||
|
||||
@classmethod
|
||||
def _local_now(cls, timezone_name: str) -> datetime:
|
||||
return datetime.now(ZoneInfo(timezone_name))
|
||||
|
||||
@classmethod
|
||||
def _next_run_at(cls, now_local: datetime, hour: int, minute: int) -> datetime:
|
||||
scheduled = now_local.replace(hour=hour, minute=minute, second=0, microsecond=0)
|
||||
if now_local >= scheduled:
|
||||
scheduled = scheduled + timedelta(days=1)
|
||||
return scheduled
|
||||
|
||||
@classmethod
|
||||
def _worker_loop(cls, app) -> None:
|
||||
with app.app_context():
|
||||
timezone_name = str(app.config.get("FIXED_ASSETS_SYNC_TIMEZONE") or "Asia/Shanghai").strip()
|
||||
schedule_hour = int(app.config.get("FIXED_ASSETS_SYNC_HOUR", 3) or 3)
|
||||
schedule_minute = int(app.config.get("FIXED_ASSETS_SYNC_MINUTE", 0) or 0)
|
||||
poll_seconds = max(30, int(app.config.get("FIXED_ASSETS_SYNC_POLL_SECONDS", 60) or 60))
|
||||
if cls._should_run_bootstrap():
|
||||
try:
|
||||
cls.sync_with_retry(reason="bootstrap")
|
||||
except Exception as exc: # pragma: no cover - runtime branch
|
||||
cls._log("warning", f"Bootstrap fixed assets snapshot failed: {exc}")
|
||||
|
||||
next_run = cls._next_run_at(cls._local_now(timezone_name), schedule_hour, schedule_minute)
|
||||
while True: # pragma: no cover - runtime branch
|
||||
now_local = cls._local_now(timezone_name)
|
||||
if now_local >= next_run:
|
||||
try:
|
||||
cls.sync_with_retry(reason="schedule")
|
||||
except Exception as exc:
|
||||
cls._log("warning", f"Scheduled fixed assets snapshot failed: {exc}")
|
||||
next_run = cls._next_run_at(cls._local_now(timezone_name), schedule_hour, schedule_minute)
|
||||
time.sleep(poll_seconds)
|
||||
|
||||
@classmethod
|
||||
def start_worker(cls, app) -> None:
|
||||
"""启动固定资产快照后台同步线程。"""
|
||||
global _worker_started
|
||||
if not bool(app.config.get("FIXED_ASSETS_SYNC_ENABLED", True)):
|
||||
app.logger.info("Fixed assets snapshot worker disabled by config")
|
||||
return
|
||||
with _worker_lock:
|
||||
if _worker_started:
|
||||
return
|
||||
thread = threading.Thread(
|
||||
target=cls._worker_loop,
|
||||
args=(app,),
|
||||
name="fixed-assets-snapshot-worker",
|
||||
daemon=True,
|
||||
)
|
||||
thread.start()
|
||||
_worker_started = True
|
||||
app.logger.info("Fixed assets snapshot worker started")
|
||||
|
||||
@staticmethod
|
||||
def _log(level: str, message: str) -> None:
|
||||
if has_app_context():
|
||||
getattr(current_app.logger, level, current_app.logger.info)(message)
|
||||
|
||||
@@ -22,21 +22,19 @@ backend/app/services/hot_faq_aggregator.py
|
||||
|
||||
## 最佳答案选取规则(HOT_FAQ_ANSWER_RULES)
|
||||
|
||||
1. **答案聚类**:对组内每条 ChatLog 的 answer 做相似度聚类(SequenceMatcher ≥ FAQ_HOT_ANSWER_SIMILARITY,默认 0.95)。
|
||||
2. **一致性门槛**:最大簇占比 ≥ FAQ_HOT_ANSWER_DOMINANCE(默认 0.6);否则视为答案分歧过大,整组跳过。
|
||||
3. **在最大簇内选代表答案**,优先级:
|
||||
1. ~~**答案聚类**~~(已暂时关闭):原按 FAQ_HOT_ANSWER_SIMILARITY 对 answer 聚类。
|
||||
2. ~~**一致性门槛**~~(已暂时关闭):原要求最大簇占比 ≥ FAQ_HOT_ANSWER_DOMINANCE。
|
||||
3. **在组内选代表答案**,优先级:
|
||||
a. Feedback.score ≥ FAQ_HOT_GOOD_SCORE(默认 4)的记录中,取 created_at 最新;
|
||||
b. 否则排除 Feedback.score ≤ FAQ_HOT_BAD_SCORE(默认 2)的记录,取 created_at 最新;
|
||||
c. 否则取簇内 created_at 最新的 answer。
|
||||
c. 否则取组内 created_at 最新的 answer。
|
||||
4. **canonical_query**:取该组内出现次数最多的原始 query 文本(非归一化,便于人工阅读)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from collections import Counter, defaultdict
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime, timedelta
|
||||
from difflib import SequenceMatcher
|
||||
from typing import Any, Optional
|
||||
|
||||
from flask import current_app
|
||||
@@ -73,8 +71,7 @@ HOT_FAQ_AGGREGATOR_DOC_SELECTION = (
|
||||
)
|
||||
|
||||
HOT_FAQ_AGGREGATOR_DOC_ANSWER = (
|
||||
'答案按相似度聚类,最大簇占比需≥dominance 阈值;'
|
||||
'在最大簇内优先选好评最新,其次无差评最新,最后取最新记录。'
|
||||
'答案聚类与一致性门槛已暂时关闭;在组内按反馈优先级选代表答案。'
|
||||
)
|
||||
|
||||
|
||||
@@ -161,8 +158,10 @@ class HotFaqAggregator:
|
||||
'description': HOT_FAQ_AGGREGATOR_DOC_SELECTION,
|
||||
},
|
||||
'answer': {
|
||||
# 答案聚类 / 一致性门槛已暂时关闭,以下配置保留供日后恢复
|
||||
'answer_similarity': float(cls._cfg('FAQ_HOT_ANSWER_SIMILARITY', 0.95)),
|
||||
'answer_dominance': float(cls._cfg('FAQ_HOT_ANSWER_DOMINANCE', 0.6)),
|
||||
'answer_clustering_enabled': False,
|
||||
'good_feedback_score': int(cls._cfg('FAQ_HOT_GOOD_SCORE', 4)),
|
||||
'bad_feedback_score': int(cls._cfg('FAQ_HOT_BAD_SCORE', 2)),
|
||||
'description': HOT_FAQ_AGGREGATOR_DOC_ANSWER,
|
||||
@@ -332,17 +331,19 @@ class HotFaqAggregator:
|
||||
rows: list[_LogRow],
|
||||
) -> tuple[Optional[HotFaqCandidate], Optional[str]]:
|
||||
"""从一组 ChatLog 构建热点候选;失败时返回 skip reason。"""
|
||||
dominance_threshold = float(cls._cfg('FAQ_HOT_ANSWER_DOMINANCE', 0.6))
|
||||
clusters = cls._cluster_answers(rows)
|
||||
if not clusters:
|
||||
return None, 'empty_answer_clusters'
|
||||
# [DISABLED] 答案聚类 + 一致性门槛(answer_divergence)已暂时关闭,直接在整组内选代表答案。
|
||||
# dominance_threshold = float(cls._cfg('FAQ_HOT_ANSWER_DOMINANCE', 0.6))
|
||||
# similarity_threshold = float(cls._cfg('FAQ_HOT_ANSWER_SIMILARITY', 0.95))
|
||||
# largest_rows = cls._largest_similarity_cluster(rows, similarity_threshold)
|
||||
# dominance = len(largest_rows) / len(rows) if rows else 0.0
|
||||
# if dominance < dominance_threshold:
|
||||
# relaxed = float(cls._cfg('FAQ_HOT_ANSWER_SIMILARITY_RELAXED', 0.70))
|
||||
# ...
|
||||
# if dominance < dominance_threshold:
|
||||
# return None, f'answer_divergence:{dominance:.2f}'
|
||||
|
||||
largest = max(clusters, key=lambda c: len(c['rows']))
|
||||
dominance = len(largest['rows']) / len(rows)
|
||||
if dominance < dominance_threshold:
|
||||
return None, f'answer_divergence:{dominance:.2f}'
|
||||
|
||||
rep = cls._pick_representative_answer(largest['rows'])
|
||||
dominance = 1.0
|
||||
rep = cls._pick_representative_answer(rows)
|
||||
if not rep:
|
||||
return None, 'no_representative_answer'
|
||||
|
||||
@@ -371,44 +372,25 @@ class HotFaqAggregator:
|
||||
retriever_resources=rep.retriever_resources,
|
||||
), None
|
||||
|
||||
@classmethod
|
||||
def _cluster_answers(cls, rows: list[_LogRow]) -> list[dict[str, Any]]:
|
||||
"""
|
||||
将 answer 按相似度聚类(贪心:与簇代表相似度 ≥ 阈值则归入)。
|
||||
@returns [{'representative': str, 'rows': [_LogRow, ...]}, ...]
|
||||
"""
|
||||
threshold = float(cls._cfg('FAQ_HOT_ANSWER_SIMILARITY', 0.95))
|
||||
clusters: list[dict[str, Any]] = []
|
||||
|
||||
for row in rows:
|
||||
answer = row.answer.strip()
|
||||
if not answer:
|
||||
continue
|
||||
placed = False
|
||||
for cluster in clusters:
|
||||
rep = cluster['representative']
|
||||
if cls._answer_similarity(rep, answer) >= threshold:
|
||||
cluster['rows'].append(row)
|
||||
placed = True
|
||||
break
|
||||
if not placed:
|
||||
clusters.append({'representative': answer, 'rows': [row]})
|
||||
return clusters
|
||||
|
||||
@staticmethod
|
||||
def _answer_similarity(a: str, b: str) -> float:
|
||||
"""计算两段答案文本相似度(0~1)。"""
|
||||
left = re.sub(r'\s+', ' ', a.strip())
|
||||
right = re.sub(r'\s+', ' ', b.strip())
|
||||
if not left or not right:
|
||||
return 0.0
|
||||
return SequenceMatcher(None, left, right).ratio()
|
||||
# [DISABLED] 答案聚类相关方法(恢复 FAQ_HOT_ANSWER_SIMILARITY / DOMINANCE 检查时可启用)
|
||||
#
|
||||
# @classmethod
|
||||
# def _largest_similarity_cluster(cls, rows: list[_LogRow], threshold: float) -> list[_LogRow]:
|
||||
# ...
|
||||
#
|
||||
# @classmethod
|
||||
# def _cluster_answers(cls, rows: list[_LogRow], *, threshold: float | None = None) -> list[dict[str, Any]]:
|
||||
# ...
|
||||
#
|
||||
# @staticmethod
|
||||
# def _answer_similarity(a: str, b: str) -> float:
|
||||
# ...
|
||||
|
||||
@classmethod
|
||||
def _pick_representative_answer(cls, rows: list[_LogRow]) -> Optional[_LogRow]:
|
||||
"""
|
||||
在 dominant 簇内按反馈优先级选取最佳 ChatLog 行。
|
||||
优先级:好评最新 > 无差评最新 > 簇内最新。
|
||||
在组内按反馈优先级选取最佳 ChatLog 行。
|
||||
优先级:好评最新 > 无差评最新 > 组内最新。
|
||||
"""
|
||||
good_score = int(cls._cfg('FAQ_HOT_GOOD_SCORE', 4))
|
||||
bad_score = int(cls._cfg('FAQ_HOT_BAD_SCORE', 2))
|
||||
|
||||
@@ -10,6 +10,7 @@ import re
|
||||
from pathlib import Path
|
||||
|
||||
import requests
|
||||
from flask import current_app
|
||||
|
||||
from app import db
|
||||
from app.models import KbDifySyncRecord, KbDocumentVersion, KbGroup
|
||||
@@ -312,6 +313,7 @@ def sync_document_version_to_dify(document_version_id: int, synced_by_id: int |
|
||||
.order_by(KbDifySyncRecord.updated_at.desc(), KbDifySyncRecord.id.desc())
|
||||
.first()
|
||||
)
|
||||
previous_sync_hash = existing_record.sync_hash if existing_record else None
|
||||
|
||||
remote_document_id = None
|
||||
remote_document_name = None
|
||||
@@ -401,6 +403,35 @@ def sync_document_version_to_dify(document_version_id: int, synced_by_id: int |
|
||||
|
||||
record.synced_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
|
||||
content_changed = previous_sync_hash != sync_hash
|
||||
if content_changed:
|
||||
try:
|
||||
from app.services.faq_kb_invalidation import (
|
||||
STALE_REASON_KB_UPDATED,
|
||||
invalidate_faqs_for_kb_document,
|
||||
)
|
||||
|
||||
invalidated = invalidate_faqs_for_kb_document(
|
||||
document.id,
|
||||
reason=STALE_REASON_KB_UPDATED,
|
||||
dataset_id=str(dataset_id),
|
||||
remote_document_id=str(remote_document_id),
|
||||
)
|
||||
if current_app and invalidated:
|
||||
current_app.logger.info(
|
||||
'[faq-kb-invalidation] kb_document_updated id=%s invalidated=%s',
|
||||
document.id,
|
||||
invalidated,
|
||||
)
|
||||
except Exception as exc:
|
||||
if current_app:
|
||||
current_app.logger.warning(
|
||||
'[faq-kb-invalidation] hook failed document_id=%s: %s',
|
||||
document.id,
|
||||
exc,
|
||||
)
|
||||
|
||||
return {
|
||||
'dataset_id': dataset_id,
|
||||
'dataset_name': dataset_name,
|
||||
@@ -445,4 +476,32 @@ def delete_document_from_dify(document_id: int) -> dict:
|
||||
deleted_count += 1
|
||||
|
||||
db.session.commit()
|
||||
|
||||
try:
|
||||
from app.services.faq_kb_invalidation import (
|
||||
STALE_REASON_KB_DELETED,
|
||||
invalidate_faqs_for_kb_document,
|
||||
)
|
||||
|
||||
latest = records[0] if records else None
|
||||
invalidated = invalidate_faqs_for_kb_document(
|
||||
int(document_id),
|
||||
reason=STALE_REASON_KB_DELETED,
|
||||
dataset_id=str(latest.dataset_id) if latest and latest.dataset_id else None,
|
||||
remote_document_id=str(latest.remote_document_id) if latest and latest.remote_document_id else None,
|
||||
)
|
||||
if current_app and invalidated:
|
||||
current_app.logger.info(
|
||||
'[faq-kb-invalidation] kb_document_deleted id=%s invalidated=%s',
|
||||
document_id,
|
||||
invalidated,
|
||||
)
|
||||
except Exception as exc:
|
||||
if current_app:
|
||||
current_app.logger.warning(
|
||||
'[faq-kb-invalidation] delete hook failed document_id=%s: %s',
|
||||
document_id,
|
||||
exc,
|
||||
)
|
||||
|
||||
return {'deleted': True, 'remote_document_count': deleted_count}
|
||||
@@ -273,6 +273,9 @@ def list_registered_api_paths() -> list[dict[str, str]]:
|
||||
|
||||
def resolve_schedule_executor(task: ScheduleTask) -> ScheduleExecutor:
|
||||
dst = getattr(task, "data_source_type", None) or "database"
|
||||
if dst == "faq_hot_aggregate":
|
||||
from app.services.schedule.faq_hot_aggregate_job import run_faq_hot_aggregate_schedule
|
||||
return run_faq_hot_aggregate_schedule
|
||||
if dst in ("database", "external_api"):
|
||||
return _run_generic_check_job
|
||||
return _run_common_executor
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
"""
|
||||
backend/app/services/schedule/faq_hot_aggregate_job.py
|
||||
|
||||
用途:排程管理触发的 FAQ 热点离线聚合执行器。
|
||||
依赖:HotFaqAggregator、ScheduleTask、ScheduleRun。
|
||||
逻辑:data_source_type=faq_hot_aggregate 时由 resolve_schedule_executor 调用。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
from app.services.hot_faq_aggregator import HotFaqAggregator
|
||||
|
||||
ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str], list[dict[str, Any]]]
|
||||
|
||||
|
||||
def run_faq_hot_aggregate_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
|
||||
"""
|
||||
执行 FAQ 热点离线聚合(等同 flask faq-aggregate-hot,非 dry-run)。
|
||||
核心逻辑:委托 HotFaqAggregator;可选 dify_agent_id 限定 Agent。
|
||||
@param task - 排程任务;dify_agent_id 可选作 agent_id 过滤
|
||||
@param run - 当前执行批次(未写入 run 字段,由 scheduler_service 汇总)
|
||||
@returns ScheduleExecuteResult 元组
|
||||
"""
|
||||
agent_id = int(task.dify_agent_id) if task.dify_agent_id else None
|
||||
result = HotFaqAggregator.aggregate_hot_faq_candidates(agent_id=agent_id, dry_run=False)
|
||||
|
||||
step_logs: list[dict[str, Any]] = [
|
||||
{
|
||||
'step': 'faq_hot_aggregate',
|
||||
'status': 'started',
|
||||
'detail': {'schedule_task_id': task.id, 'agent_id': agent_id},
|
||||
}
|
||||
]
|
||||
|
||||
if not result.get('enabled'):
|
||||
message = str(result.get('message') or 'FAQ_HOT_ENABLED is false')
|
||||
step_logs.append({'step': 'faq_hot_aggregate', 'status': 'skipped', 'detail': {'message': message}})
|
||||
return 0, 0, 0, 1, [], [message], step_logs
|
||||
|
||||
promoted = int(result.get('promoted_count') or 0)
|
||||
skipped = int(result.get('skipped_count') or 0)
|
||||
scanned = int(result.get('scanned_logs') or 0)
|
||||
total = max(promoted + skipped, 1)
|
||||
|
||||
step_logs.append({
|
||||
'step': 'faq_hot_aggregate',
|
||||
'status': 'success',
|
||||
'detail': {
|
||||
'scanned_logs': scanned,
|
||||
'promoted_count': promoted,
|
||||
'skipped_count': skipped,
|
||||
'group_count': result.get('group_count'),
|
||||
'agent_id': agent_id,
|
||||
},
|
||||
})
|
||||
|
||||
details = [
|
||||
{
|
||||
'canonical_query': item.get('canonical_query'),
|
||||
'ask_count_7d': item.get('ask_count_7d'),
|
||||
'user_count_7d': item.get('user_count_7d'),
|
||||
'answer_dominance': item.get('answer_dominance'),
|
||||
}
|
||||
for item in (result.get('candidates') or [])[:20]
|
||||
if isinstance(item, dict)
|
||||
]
|
||||
|
||||
return total, promoted, 0, skipped, details, [], step_logs
|
||||
@@ -226,7 +226,10 @@ def update_task(task: ScheduleTask, *, payload: dict[str, Any], actor_id: int |
|
||||
task.kb_group_id = int(raw_group_id) if raw_group_id not in (None, "", 0, "0") else None
|
||||
|
||||
if not normalize_platform_api_path(task.platform_api_path):
|
||||
raise ValueError("platform_api_path is required for platform_app")
|
||||
dst = str(getattr(task, "data_source_type", None) or "database")
|
||||
if dst != "faq_hot_aggregate":
|
||||
raise ValueError("platform_api_path is required for platform_app")
|
||||
task.platform_api_path = "faq-aggregate-hot"
|
||||
task.schedule_type = "platform_app"
|
||||
|
||||
if task.enabled and task.cron_expr:
|
||||
|
||||
@@ -76,6 +76,23 @@ class Text2SQLService:
|
||||
"GEM01": "部门编号",
|
||||
"GEM02": "部门名称",
|
||||
}
|
||||
_ASSET_DISPLAY_COLUMN_ORDER = (
|
||||
"资产编号",
|
||||
"资产名称",
|
||||
"规格型号",
|
||||
"保管人姓名",
|
||||
"保管部门名称",
|
||||
"存放位置名称",
|
||||
"资产状态",
|
||||
"预留残值",
|
||||
"供应厂商",
|
||||
"资产性质",
|
||||
"本币单价",
|
||||
"数量",
|
||||
"计量单位",
|
||||
"取得日期",
|
||||
"入账日期",
|
||||
)
|
||||
_ASSET_VALUE_MAPPINGS = {
|
||||
"资产性质": {
|
||||
"1": "有形资产",
|
||||
@@ -460,6 +477,58 @@ class Text2SQLService:
|
||||
def _is_asset_management_agent(cls, agent) -> bool:
|
||||
return cls._agent_name(agent) in cls._ASSET_AGENT_NAMES
|
||||
|
||||
@classmethod
|
||||
def _refine_asset_query(cls, query: str, agent=None) -> str:
|
||||
"""使用固资查询提炼 Agent 清洗用户问句。
|
||||
|
||||
AI 触发时机:当用户在固资查询中夹带“生成图表、生成 Excel、生成表单”等
|
||||
与数据筛选无关的诉求时,先提炼出纯查询文字,再交给现有固资规则和 Text2SQL 流程。
|
||||
|
||||
Args:
|
||||
query: 用户原始问题,允许同时包含查询、统计、导出或展示诉求。
|
||||
agent: 当前会话 Agent,仅固资管理 Agent 进入该提炼流程。
|
||||
|
||||
Returns:
|
||||
str: 提炼后的查询文字;若不属于固资 Agent、模型调用失败或结果无效,则回退原问题。
|
||||
"""
|
||||
original_query = str(query or "").strip()
|
||||
if not original_query:
|
||||
return ""
|
||||
if not cls._is_asset_management_agent(agent):
|
||||
return original_query
|
||||
|
||||
system_prompt = """你是一位文字提炼专家。
|
||||
|
||||
# 角色
|
||||
你是一位文字提炼专家
|
||||
|
||||
# 任务
|
||||
负责把用户的查询数据需求进行提炼和总结,抓取关键数据查询文字,去掉和数据查询无关的内容,比如生成图表、生成Excel、生成表单等和数据查询无关的内容,只保留提炼查询数据的文字。
|
||||
|
||||
# 约束
|
||||
- 只保留与固定资产数据查询直接相关的文字。
|
||||
- 保留用户的筛选条件、模糊查询关键词、统计意图,例如“有多少”“多少台”“明细”“列表”。
|
||||
- 删除生成图表、生成 Excel、生成表单、导出、汇报、分析结论、排版等与查询无关的内容。
|
||||
- 用户在查询设备固资时可按:资产编号、资产名称、规格型号、资产性质、保管人、保管部门、存放位置、资产状态、供应厂商进行模糊查询。
|
||||
- 像“线切割机”“线切割机有多少”“400吨冲床有多少台”这类表达属于有效查询意图,必须保留。
|
||||
- 如果原问题已经是纯查询表达,直接原样输出。
|
||||
- 不要补充不存在的筛选条件,不要解释,不要加引号,不要输出多段内容。
|
||||
|
||||
# 输出
|
||||
只输出你提炼后的结果,无需其他言语。"""
|
||||
user_prompt = f"用户原始问题:{original_query}"
|
||||
|
||||
try:
|
||||
refined_query = cls._chat_completion(system_prompt, user_prompt, temperature=0)
|
||||
except Exception as exc:
|
||||
cls._log("warning", f"Asset query refine failed, fallback to original query: {exc}")
|
||||
return original_query
|
||||
|
||||
refined_query = re.sub(r"\s+", " ", str(refined_query or "")).strip().strip("`'\"")
|
||||
if len(refined_query) < 2:
|
||||
return original_query
|
||||
return refined_query
|
||||
|
||||
@classmethod
|
||||
def _looks_like_asset_query(cls, query: str, sql: str = "") -> bool:
|
||||
query_text = str(query or "")
|
||||
@@ -494,6 +563,84 @@ class Text2SQLService:
|
||||
text = re.sub(r"(?:的|下)?(?:有哪些|有多少|多少|名下|资产|固定资产|固资|列表|明细|电脑|设备|机|工装|模具|车辆).*$", "", text)
|
||||
return text.strip(" ::,,。.??")
|
||||
|
||||
@classmethod
|
||||
def _clean_asset_keyword_value(cls, value: str | None) -> str:
|
||||
"""清洗固资名称/规格等自由输入关键词,尽量保留设备名原词。"""
|
||||
text = cls._strip_asset_query_prefix(value)
|
||||
text = re.sub(r"(?:有多少台?|有多少|多少台?|多少|有哪些|有什么|明细|列表|数据|结果).*$", "", text)
|
||||
text = re.sub(r"^(?:请问|帮我|看下|查下|查询|统计|核对|看看|我想知道)\s*", "", text)
|
||||
return text.strip(" ::,,。.??;;")
|
||||
|
||||
@classmethod
|
||||
def _extract_explicit_asset_name(cls, query: str) -> str:
|
||||
"""抽取用户显式声明的资产名称。"""
|
||||
text = cls._strip_asset_query_prefix(query)
|
||||
if not text:
|
||||
return ""
|
||||
patterns = [
|
||||
r"(?:资产名称|设备名称|固定资产名称|固资名称)\s*(?:为|是|叫|=|:|:)?\s*([A-Za-z0-9\u4e00-\u9fff()()\-_]{2,40})",
|
||||
r"^\s*([A-Za-z0-9\u4e00-\u9fff()()\-_]{2,40})\s*(?:的)?\s*(?:规格型号|规格|型号)",
|
||||
]
|
||||
for pattern in patterns:
|
||||
match = re.search(pattern, text)
|
||||
if not match:
|
||||
continue
|
||||
candidate = cls._clean_asset_keyword_value(match.group(1))
|
||||
if not candidate:
|
||||
continue
|
||||
if cls._looks_like_asset_code_token(candidate):
|
||||
continue
|
||||
if cls._ASSET_SUFFIX_DEPARTMENT_PATTERN.fullmatch(candidate):
|
||||
continue
|
||||
if cls._looks_like_person_name(candidate):
|
||||
continue
|
||||
return candidate
|
||||
return ""
|
||||
|
||||
@classmethod
|
||||
def _extract_asset_name_combo_keyword(cls, query: str) -> str:
|
||||
"""在“资产名称/编号 + 规格型号”等组合问句中补抽资产名称。"""
|
||||
text = cls._strip_asset_query_prefix(query)
|
||||
if not text:
|
||||
return ""
|
||||
|
||||
stripped = text
|
||||
patterns_to_strip = [
|
||||
r"(?:规格型号|规格|型号)(?:为|是|叫|=|:|:)?\s*[A-Za-z0-9\u4e00-\u9fff()()\-_*.-]+",
|
||||
r"(?:资产类型|类型)(?:为|是|叫|=|:|:)?\s*[A-Za-z0-9\u4e00-\u9fff()()\-_*.-]+",
|
||||
r"(?:资产状态|状态)(?:为|是|叫|=|:|:)?\s*[A-Za-z0-9\u4e00-\u9fff()()\-_*.-]+",
|
||||
r"(?:存放位置|位置)(?:在|为|是|叫|=|:|:)?\s*[A-Za-z0-9\u4e00-\u9fff()()\-_*.-]+",
|
||||
r"(?:供应商|供应厂商|厂商)(?:为|是|叫|=|:|:)?\s*[A-Za-z0-9\u4e00-\u9fff()()\-_*.-]+",
|
||||
r"(?:资产名称|设备名称|固定资产名称|固资名称)\s*(?:为|是|叫|=|:|:)?\s*[A-Za-z0-9\u4e00-\u9fff()()\-_*.-]+",
|
||||
]
|
||||
for pattern in patterns_to_strip:
|
||||
stripped = re.sub(pattern, " ", stripped)
|
||||
|
||||
asset_code = cls._extract_asset_code(text)
|
||||
if asset_code:
|
||||
stripped = re.sub(re.escape(asset_code), " ", stripped, flags=re.IGNORECASE)
|
||||
|
||||
stripped = re.sub(
|
||||
r"(?:固定资产|固资|资产编号|财产编号|资产编码|编号|资产名称|设备名称|资产|设备|请问|帮我|看下|查下|查询|统计|核对|看看|我想知道|有多少台?|有多少|多少台?|多少|明细|列表|数据|结果|并且|且|以及|还有|和|按|根据)",
|
||||
" ",
|
||||
stripped,
|
||||
)
|
||||
candidates = re.findall(r"[A-Za-z0-9\u4e00-\u9fff()()\-_]{2,40}", stripped)
|
||||
for candidate in sorted(candidates, key=len, reverse=True):
|
||||
cleaned = cls._clean_asset_keyword_value(candidate)
|
||||
if not cleaned:
|
||||
continue
|
||||
if cleaned in {"公司", "全部", "所有", "当前", "目前"}:
|
||||
continue
|
||||
if cls._looks_like_asset_code_token(cleaned):
|
||||
continue
|
||||
if cls._ASSET_SUFFIX_DEPARTMENT_PATTERN.fullmatch(cleaned):
|
||||
continue
|
||||
if cls._looks_like_person_name(cleaned):
|
||||
continue
|
||||
return cleaned
|
||||
return ""
|
||||
|
||||
@classmethod
|
||||
def _extract_advanced_asset_conditions(cls, query: str) -> dict[str, str]:
|
||||
conds = {}
|
||||
@@ -522,7 +669,20 @@ class Text2SQLService:
|
||||
if m:
|
||||
val = cls._clean_asset_scope_value(m.group(1))
|
||||
if val: conds["vendor"] = val
|
||||
|
||||
|
||||
explicit_asset_name = cls._extract_explicit_asset_name(query)
|
||||
if explicit_asset_name:
|
||||
conds["asset_name"] = explicit_asset_name
|
||||
|
||||
asset_code = cls._extract_asset_code(query)
|
||||
if asset_code and conds:
|
||||
conds["asset_code"] = asset_code
|
||||
|
||||
if conds and "asset_name" not in conds:
|
||||
combo_asset_name = cls._extract_asset_name_combo_keyword(query)
|
||||
if combo_asset_name:
|
||||
conds["asset_name"] = combo_asset_name
|
||||
|
||||
return conds
|
||||
|
||||
@staticmethod
|
||||
@@ -639,7 +799,7 @@ class Text2SQLService:
|
||||
match = re.search(pattern, text)
|
||||
if not match:
|
||||
continue
|
||||
keyword = cls._clean_asset_scope_value(match.group("keyword"))
|
||||
keyword = cls._clean_asset_keyword_value(match.group("keyword"))
|
||||
if not keyword:
|
||||
continue
|
||||
if keyword in {"公司", "全部", "所有", "当前", "目前"}:
|
||||
@@ -653,7 +813,7 @@ class Text2SQLService:
|
||||
return keyword
|
||||
|
||||
if re.fullmatch(r"^\s*[A-Za-z0-9\u4e00-\u9fff()()\-_]{2,40}\s*$", text):
|
||||
cleaned = cls._clean_asset_scope_value(text)
|
||||
cleaned = cls._clean_asset_keyword_value(text)
|
||||
if cleaned and cleaned not in {"公司", "全部", "所有", "当前", "目前", "你好", "在吗", "是谁", "是什么", "固定资产", "固资", "资产", "设备"}:
|
||||
if not cls._looks_like_person_name(cleaned) and not cls._ASSET_SUFFIX_DEPARTMENT_PATTERN.fullmatch(cleaned):
|
||||
return cleaned
|
||||
@@ -957,6 +1117,17 @@ ORDER BY faj.faj02
|
||||
nature_sql = f"\n AND {nature_condition}" if nature_condition else ""
|
||||
|
||||
where_clauses = []
|
||||
if "asset_code" in conds:
|
||||
literal = cls._escape_sql_literal(conds["asset_code"])
|
||||
where_clauses.append(f"UPPER(NVL(faj.faj02, ' ')) LIKE '%' || UPPER('{literal}') || '%'")
|
||||
if "asset_name" in conds:
|
||||
literal = cls._escape_sql_literal(conds["asset_name"])
|
||||
where_clauses.append(
|
||||
"("
|
||||
f"UPPER(NVL(faj.faj06, ' ')) LIKE '%' || UPPER('{literal}') || '%' "
|
||||
f"OR UPPER(NVL(faj.faj061, ' ')) LIKE '%' || UPPER('{literal}') || '%'"
|
||||
")"
|
||||
)
|
||||
if "spec" in conds:
|
||||
literal = cls._escape_sql_literal(conds["spec"])
|
||||
where_clauses.append(f"UPPER(NVL(faj.faj08, ' ')) LIKE '%' || UPPER('{literal}') || '%'")
|
||||
@@ -1088,7 +1259,7 @@ ORDER BY faj.faj02
|
||||
"- 固资相关联表必须同时补齐 `site` 条件,例如 `gen.site = faj.site`、`gem.site = faj.site`、`faf.site = faj.site`、`fab.site = faj.site`、`pmc.site = faj.site`,避免同编码跨营运中心造成重复记录。",
|
||||
"- 固资数据只允许保留 `faj22`(存放营运中心)属于 `HXJM`、`HTT`、`HTE` 的记录;生成 SQL 时必须显式加上 `UPPER(TRIM(NVL(faj.faj22, ''))) IN ('HXJM', 'HTT', 'HTE')` 过滤。",
|
||||
"- 查询固定资产明细列表时优先使用 `SELECT DISTINCT`;如果是统计资产数量,优先使用 `COUNT(DISTINCT faj.faj02)`。",
|
||||
"- 当查询固定资产明细时,返回结果必须且只能包含以下列并使用严格对应的中文别名:faj.faj02 AS \"资产编号\"、faj.faj06 AS \"资产名称\"、faj.faj08 AS \"规格型号\"、faj.faj09 AS \"资产性质\"、faj.faj13 AS \"本币单价\"、faj.faj17 AS \"数量\"、faj.faj18 AS \"计量单位\"、TO_CHAR(faj.faj25, YYYY-MM-DD HH24:MI:SS) AS \"取得日期\"、TO_CHAR(faj.faj26, YYYY-MM-DD HH24:MI:SS) AS \"入账日期\"、gen.gen02 AS \"保管人姓名\"、gem.gem02 AS \"保管部门名称\"、faf.faf02 AS \"存放位置名称\"、faj.faj43 AS \"资产状态\"、faj.faj31 AS \"预留残值\"、pmc.pmc03 AS \"供应厂商\"。",
|
||||
"- 当查询固定资产明细时,返回结果必须且只能包含以下列并使用严格对应的中文别名,顺序必须为:faj.faj02 AS \"资产编号\"、faj.faj06 AS \"资产名称\"、faj.faj08 AS \"规格型号\"、gen.gen02 AS \"保管人姓名\"、gem.gem02 AS \"保管部门名称\"、faf.faf02 AS \"存放位置名称\"、faj.faj43 AS \"资产状态\"、faj.faj31 AS \"预留残值\"、pmc.pmc03 AS \"供应厂商\"、faj.faj09 AS \"资产性质\"、faj.faj13 AS \"本币单价\"、faj.faj17 AS \"数量\"、faj.faj18 AS \"计量单位\"、TO_CHAR(faj.faj25, YYYY-MM-DD HH24:MI:SS) AS \"取得日期\"、TO_CHAR(faj.faj26, YYYY-MM-DD HH24:MI:SS) AS \"入账日期\"。",
|
||||
"- 日期时间字段展示时不要去掉时分秒;若使用 TO_CHAR 格式化,必须保留为 `YYYY-MM-DD HH24:MI:SS`,不能只输出日期。",
|
||||
*filters,
|
||||
]
|
||||
@@ -1098,12 +1269,36 @@ ORDER BY faj.faj02
|
||||
def _localize_asset_columns(cls, columns, query: str, sql: str, agent=None):
|
||||
if not (cls._is_asset_management_agent(agent) or cls._looks_like_asset_query(query, sql)):
|
||||
return columns
|
||||
localized = cls._map_asset_column_names(columns)
|
||||
order = cls._get_asset_display_order(columns, query, sql, agent=agent)
|
||||
return [localized[idx] for idx in order]
|
||||
|
||||
@classmethod
|
||||
def _map_asset_column_names(cls, columns):
|
||||
localized = []
|
||||
for name in columns or []:
|
||||
raw_name = str(name or "").strip().strip('"')
|
||||
localized.append(cls._ASSET_COLUMN_LABELS.get(raw_name.upper(), raw_name))
|
||||
return localized
|
||||
|
||||
@classmethod
|
||||
def _get_asset_display_order(cls, columns, query: str, sql: str, agent=None) -> list[int]:
|
||||
if not (cls._is_asset_management_agent(agent) or cls._looks_like_asset_query(query, sql)):
|
||||
return list(range(len(columns or [])))
|
||||
localized = cls._map_asset_column_names(columns)
|
||||
normalized_target_order = {
|
||||
cls._normalize_result_column_name(name): position
|
||||
for position, name in enumerate(cls._ASSET_DISPLAY_COLUMN_ORDER)
|
||||
}
|
||||
indexed_columns = list(enumerate(localized))
|
||||
indexed_columns.sort(
|
||||
key=lambda item: (
|
||||
normalized_target_order.get(cls._normalize_result_column_name(item[1]), len(normalized_target_order) + item[0]),
|
||||
item[0],
|
||||
)
|
||||
)
|
||||
return [idx for idx, _ in indexed_columns]
|
||||
|
||||
@classmethod
|
||||
def _translate_asset_display_value(cls, display_name: str, value) -> str:
|
||||
text = cls._stringify_value(value)
|
||||
@@ -1118,7 +1313,7 @@ ORDER BY faj.faj02
|
||||
|
||||
@classmethod
|
||||
def _find_result_column_index(cls, columns, query: str, sql: str, agent, candidate_names: set[str]) -> int | None:
|
||||
localized_columns = cls._localize_asset_columns(columns, query, sql, agent=agent)
|
||||
localized_columns = cls._map_asset_column_names(columns)
|
||||
for idx, raw_name in enumerate(columns or []):
|
||||
normalized_raw = cls._normalize_result_column_name(raw_name)
|
||||
normalized_localized = cls._normalize_result_column_name(localized_columns[idx] if idx < len(localized_columns) else "")
|
||||
@@ -1191,11 +1386,13 @@ ORDER BY faj.faj02
|
||||
def _localize_asset_rows(cls, columns, rows, query: str, sql: str, agent=None):
|
||||
if not (cls._is_asset_management_agent(agent) or cls._looks_like_asset_query(query, sql)):
|
||||
return rows
|
||||
display_order = cls._get_asset_display_order(columns, query, sql, agent=agent)
|
||||
display_columns = cls._localize_asset_columns(columns, query, sql, agent=agent)
|
||||
index_map = {str(name or "").strip(): idx for idx, name in enumerate(display_columns)}
|
||||
localized_rows = []
|
||||
for row in rows or []:
|
||||
row_values = list(row)
|
||||
source_row_values = list(row)
|
||||
row_values = [source_row_values[idx] if idx < len(source_row_values) else None for idx in display_order]
|
||||
display_values = []
|
||||
for idx, display_name in enumerate(display_columns):
|
||||
raw_value = row_values[idx] if idx < len(row_values) else None
|
||||
@@ -1269,9 +1466,39 @@ ORDER BY faj.faj02
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def _query_asset_total_count(cls, query: str, sql: str, agent=None) -> int | None:
|
||||
def _can_use_fixed_assets_snapshot(cls, query: str, agent=None) -> bool:
|
||||
if not (cls._is_asset_management_agent(agent) or cls._looks_like_asset_query(query, "")):
|
||||
return False
|
||||
try:
|
||||
from app.services.fixed_assets_snapshot import FixedAssetsSnapshotService
|
||||
|
||||
return FixedAssetsSnapshotService.is_snapshot_available()
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
@classmethod
|
||||
def _is_fixed_assets_snapshot_sql(cls, sql: str) -> bool:
|
||||
try:
|
||||
from app.services.fixed_assets_snapshot import FixedAssetsSnapshotService
|
||||
|
||||
return FixedAssetsSnapshotService.is_snapshot_sql(sql)
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
@classmethod
|
||||
def _query_asset_total_count(cls, query: str, sql: str, agent=None, user_context: dict | None = None) -> int | None:
|
||||
if not (cls._is_asset_management_agent(agent) or cls._looks_like_asset_query(query, sql)):
|
||||
return None
|
||||
if cls._is_fixed_assets_snapshot_sql(sql):
|
||||
from app.services.fixed_assets_snapshot import FixedAssetsSnapshotService
|
||||
|
||||
_, _, total_count = FixedAssetsSnapshotService.query_assets(
|
||||
query,
|
||||
limit=1,
|
||||
offset=0,
|
||||
user_context=user_context,
|
||||
)
|
||||
return total_count
|
||||
count_sql = cls._build_asset_total_count_sql(sql)
|
||||
if not count_sql:
|
||||
return None
|
||||
@@ -1466,8 +1693,7 @@ ORDER BY faj.faj02
|
||||
@classmethod
|
||||
def summarize_result(cls, query: str, columns, rows, total_count: int | None = None) -> str:
|
||||
if columns == ["Error"]:
|
||||
error_message = rows[0][0] if rows and rows[0] else "未知错误"
|
||||
return f"- 直击答案:查询执行失败,当前无法返回结果。\n- 异常提醒:数据库返回错误 `{error_message}`,请检查筛选条件、表名或字段名。"
|
||||
return "- 直击答案:查询执行失败,当前无法返回结果。"
|
||||
|
||||
if not rows:
|
||||
return "- 直击答案:当前未查询到符合条件的数据。\n- 趋势发现:当前结果未体现明显趋势。\n- 异常提醒:当前结果未体现明显异常,建议调整筛选条件后重试。"
|
||||
@@ -1516,12 +1742,17 @@ ORDER BY faj.faj02
|
||||
|
||||
@classmethod
|
||||
def generate_sql(cls, query: str, user_context: dict | None = None, agent=None) -> str:
|
||||
special_sql = cls._build_special_asset_sql(query, agent=agent)
|
||||
if cls._can_use_fixed_assets_snapshot(query, agent=agent):
|
||||
from app.services.fixed_assets_snapshot import FixedAssetsSnapshotService
|
||||
|
||||
return FixedAssetsSnapshotService.SNAPSHOT_SQL_MARKER
|
||||
effective_query = cls._refine_asset_query(query, agent=agent)
|
||||
special_sql = cls._build_special_asset_sql(effective_query, agent=agent)
|
||||
if special_sql:
|
||||
return cls._rewrite_asset_sql(special_sql, query, agent=agent, user_context=user_context)
|
||||
return cls._rewrite_asset_sql(special_sql, effective_query, agent=agent, user_context=user_context)
|
||||
|
||||
schema = cls.get_schema()
|
||||
asset_constraints = cls._build_asset_prompt_constraints(query, user_context, agent)
|
||||
asset_constraints = cls._build_asset_prompt_constraints(effective_query, user_context, agent)
|
||||
|
||||
try:
|
||||
system_prompt = f"""你是一个专业的 Oracle SQL 专家和数据分析助手。你的任务是将用户的自然语言转换为准确的 Oracle 查询语句。
|
||||
@@ -1542,10 +1773,10 @@ ORDER BY faj.faj02
|
||||
- 如果问题无法仅依据当前 Schema 回答,请输出安全的 SELECT 语句说明原因,例如 SELECT '无法根据当前表结构回答该问题' AS message FROM DUAL。
|
||||
{asset_constraints}"""
|
||||
|
||||
user_prompt = f"用户问题:{query}"
|
||||
user_prompt = f"用户问题:{effective_query}"
|
||||
sql = cls._chat_completion(system_prompt, user_prompt, temperature=0)
|
||||
sql = sql.rstrip(";")
|
||||
sql = cls._rewrite_asset_sql(sql, query, agent=agent, user_context=user_context)
|
||||
sql = cls._rewrite_asset_sql(sql, effective_query, agent=agent, user_context=user_context)
|
||||
|
||||
if not cls._is_safe_query(sql):
|
||||
return "SELECT 'Generated SQL was blocked because it is not a safe read-only SELECT query' AS error FROM DUAL"
|
||||
@@ -1556,14 +1787,19 @@ ORDER BY faj.faj02
|
||||
|
||||
@classmethod
|
||||
def repair_sql(cls, query: str, failed_sql: str, error_message: str, user_context: dict | None = None, agent=None) -> str:
|
||||
special_sql = cls._build_special_asset_sql(query, agent=agent)
|
||||
if cls._can_use_fixed_assets_snapshot(query, agent=agent):
|
||||
from app.services.fixed_assets_snapshot import FixedAssetsSnapshotService
|
||||
|
||||
return FixedAssetsSnapshotService.SNAPSHOT_SQL_MARKER
|
||||
effective_query = cls._refine_asset_query(query, agent=agent)
|
||||
special_sql = cls._build_special_asset_sql(effective_query, agent=agent)
|
||||
if special_sql:
|
||||
return cls._rewrite_asset_sql(special_sql, query, agent=agent, user_context=user_context)
|
||||
return cls._rewrite_asset_sql(special_sql, effective_query, agent=agent, user_context=user_context)
|
||||
|
||||
schema = cls.get_schema()
|
||||
invalid_identifier = cls._extract_invalid_identifier(error_message)
|
||||
invalid_hint = f"本次报错的非法字段/标识符是:{invalid_identifier}。" if invalid_identifier else ""
|
||||
asset_constraints = cls._build_asset_prompt_constraints(query, user_context, agent)
|
||||
asset_constraints = cls._build_asset_prompt_constraints(effective_query, user_context, agent)
|
||||
|
||||
system_prompt = f"""你是一个专业的 Oracle SQL 修复助手。你的任务是根据执行失败的 SQL、数据库报错和当前 Schema,修复成一条可执行的 Oracle 查询语句。
|
||||
|
||||
@@ -1579,7 +1815,7 @@ ORDER BY faj.faj02
|
||||
- 严禁输出任何非 SELECT / WITH 语句。
|
||||
{asset_constraints}"""
|
||||
|
||||
user_prompt = f"""用户问题:{query}
|
||||
user_prompt = f"""用户问题:{effective_query}
|
||||
执行失败的 SQL:
|
||||
```sql
|
||||
{failed_sql}
|
||||
@@ -1593,7 +1829,7 @@ ORDER BY faj.faj02
|
||||
try:
|
||||
sql = cls._chat_completion(system_prompt, user_prompt, temperature=0)
|
||||
sql = sql.rstrip(";")
|
||||
sql = cls._rewrite_asset_sql(sql, query, agent=agent, user_context=user_context)
|
||||
sql = cls._rewrite_asset_sql(sql, effective_query, agent=agent, user_context=user_context)
|
||||
if not cls._is_safe_query(sql):
|
||||
return "SELECT 'Generated SQL was blocked because it is not a safe read-only SELECT query' AS error FROM DUAL"
|
||||
return sql
|
||||
@@ -1601,7 +1837,17 @@ ORDER BY faj.faj02
|
||||
return f"SELECT '{cls._escape_sql_message(f'SQL Repair Error: {e}')}' AS error FROM DUAL"
|
||||
|
||||
@classmethod
|
||||
def execute_sql(cls, sql: str, *, query: str = "", agent=None, limit: int | None = None):
|
||||
def execute_sql(cls, sql: str, *, query: str = "", agent=None, limit: int | None = None, user_context: dict | None = None):
|
||||
if cls._is_fixed_assets_snapshot_sql(sql):
|
||||
from app.services.fixed_assets_snapshot import FixedAssetsSnapshotService
|
||||
|
||||
columns, rows, _ = FixedAssetsSnapshotService.query_assets(
|
||||
query,
|
||||
limit=limit or cls._ASSET_CHAT_RESULT_LIMIT,
|
||||
offset=0,
|
||||
user_context=user_context,
|
||||
)
|
||||
return columns, rows
|
||||
connection, cursor, columns, error_rows = cls._execute_sql_internal(sql)
|
||||
if columns == ["Error"]:
|
||||
return columns, error_rows
|
||||
@@ -1626,9 +1872,29 @@ ORDER BY faj.faj02
|
||||
connection.close()
|
||||
|
||||
@classmethod
|
||||
def execute_sql_page(cls, sql: str, *, query: str = "", page: int = 1, page_size: int = 100, agent=None):
|
||||
def execute_sql_page(
|
||||
cls,
|
||||
sql: str,
|
||||
*,
|
||||
query: str = "",
|
||||
page: int = 1,
|
||||
page_size: int = 100,
|
||||
agent=None,
|
||||
user_context: dict | None = None,
|
||||
):
|
||||
safe_page = max(1, int(page or 1))
|
||||
safe_page_size = max(1, min(200, int(page_size or 100)))
|
||||
if cls._is_fixed_assets_snapshot_sql(sql):
|
||||
from app.services.fixed_assets_snapshot import FixedAssetsSnapshotService
|
||||
|
||||
offset = (safe_page - 1) * safe_page_size
|
||||
columns, rows, _ = FixedAssetsSnapshotService.query_assets(
|
||||
query,
|
||||
limit=safe_page_size,
|
||||
offset=offset,
|
||||
user_context=user_context,
|
||||
)
|
||||
return columns, rows
|
||||
is_asset_detail = (
|
||||
not cls._is_aggregate_sql(sql)
|
||||
and (cls._is_asset_management_agent(agent) or cls._looks_like_asset_query(query, sql))
|
||||
@@ -1664,9 +1930,19 @@ ORDER BY faj.faj02
|
||||
connection.close()
|
||||
|
||||
@classmethod
|
||||
def get_total_count_for_sql(cls, sql: str) -> int | None:
|
||||
def get_total_count_for_sql(cls, sql: str, *, query: str = "", user_context: dict | None = None) -> int | None:
|
||||
if cls._is_fixed_assets_snapshot_sql(sql):
|
||||
from app.services.fixed_assets_snapshot import FixedAssetsSnapshotService
|
||||
|
||||
_, _, total_count = FixedAssetsSnapshotService.query_assets(
|
||||
query,
|
||||
limit=1,
|
||||
offset=0,
|
||||
user_context=user_context,
|
||||
)
|
||||
return total_count
|
||||
count_sql = cls._build_generic_total_count_sql(sql)
|
||||
columns, rows = cls.execute_sql_page(count_sql, page=1, page_size=1)
|
||||
columns, rows = cls.execute_sql_page(count_sql, query=query, page=1, page_size=1, user_context=user_context)
|
||||
if columns == ["Error"] or not rows or not rows[0]:
|
||||
return None
|
||||
try:
|
||||
@@ -1675,10 +1951,20 @@ ORDER BY faj.faj02
|
||||
return None
|
||||
|
||||
@classmethod
|
||||
def format_result(cls, columns, rows, sql, original_query, agent=None):
|
||||
total_count = cls._query_asset_total_count(original_query, sql, agent=agent)
|
||||
def format_result(cls, columns, rows, sql, original_query, agent=None, user_context: dict | None = None):
|
||||
total_count = cls._query_asset_total_count(original_query, sql, agent=agent, user_context=user_context)
|
||||
summary_text = cls.summarize_result(original_query, columns, rows, total_count=total_count)
|
||||
sql_details = f"<details>\n<summary class=\"cursor-pointer text-xs font-semibold uppercase tracking-wide text-slate-600 dark:text-slate-300 mb-2\">执行的SQL</summary>\n\n```sql\n{sql}\n```\n</details>"
|
||||
if cls._is_fixed_assets_snapshot_sql(sql):
|
||||
from app.services.fixed_assets_snapshot import FixedAssetsSnapshotService
|
||||
|
||||
sql_details = (
|
||||
"<details>\n"
|
||||
"<summary class=\"cursor-pointer text-xs font-semibold uppercase tracking-wide text-slate-600 dark:text-slate-300 mb-2\">数据来源</summary>\n\n"
|
||||
f"{FixedAssetsSnapshotService.snapshot_sql_label()}\n"
|
||||
"\n</details>"
|
||||
)
|
||||
else:
|
||||
sql_details = f"<details>\n<summary class=\"cursor-pointer text-xs font-semibold uppercase tracking-wide text-slate-600 dark:text-slate-300 mb-2\">执行的SQL</summary>\n\n```sql\n{sql}\n```\n</details>"
|
||||
|
||||
if columns == ["Error"]:
|
||||
error_message = rows[0][0] if rows and rows[0] else "未知错误"
|
||||
@@ -1701,10 +1987,26 @@ ORDER BY faj.faj02
|
||||
return f"{summary_text}\n\n**查询结果如下:**\n\n{table_str}\n\n{sql_details}"
|
||||
|
||||
@classmethod
|
||||
def build_query_preview_payload(cls, columns, rows, sql, original_query, agent=None):
|
||||
def build_query_preview_payload(cls, columns, rows, sql, original_query, agent=None, user_context: dict | None = None):
|
||||
if columns == ["Error"] or not columns:
|
||||
return None
|
||||
total_count = cls._query_asset_total_count(original_query, sql, agent=agent)
|
||||
if cls._is_fixed_assets_snapshot_sql(sql):
|
||||
from app.services.fixed_assets_snapshot import FixedAssetsSnapshotService
|
||||
|
||||
_, _, total_count = FixedAssetsSnapshotService.query_assets(
|
||||
original_query,
|
||||
limit=max(1, len(rows or [])),
|
||||
offset=0,
|
||||
user_context=user_context,
|
||||
)
|
||||
return FixedAssetsSnapshotService.get_snapshot_preview_payload(
|
||||
original_query,
|
||||
cls._localize_asset_columns(columns, original_query, sql, agent=agent),
|
||||
rows,
|
||||
total_count,
|
||||
)
|
||||
|
||||
total_count = cls._query_asset_total_count(original_query, sql, agent=agent, user_context=user_context)
|
||||
if total_count is None:
|
||||
total_count = len(rows or [])
|
||||
preview_row_count = len(rows or [])
|
||||
@@ -1720,11 +2022,32 @@ ORDER BY faj.faj02
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def get_preview_page(cls, *, sql: str, query: str, page: int = 1, page_size: int = 100, agent=None, total_count: int | None = None):
|
||||
raw_columns, raw_rows = cls.execute_sql_page(sql, query=query, page=page, page_size=page_size, agent=agent)
|
||||
def get_preview_page(
|
||||
cls,
|
||||
*,
|
||||
sql: str,
|
||||
query: str,
|
||||
page: int = 1,
|
||||
page_size: int = 100,
|
||||
agent=None,
|
||||
total_count: int | None = None,
|
||||
user_context: dict | None = None,
|
||||
):
|
||||
raw_columns, raw_rows = cls.execute_sql_page(
|
||||
sql,
|
||||
query=query,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
agent=agent,
|
||||
user_context=user_context,
|
||||
)
|
||||
if raw_columns == ["Error"]:
|
||||
return raw_columns, raw_rows, total_count
|
||||
resolved_total = total_count if total_count is not None else cls.get_total_count_for_sql(sql)
|
||||
resolved_total = total_count if total_count is not None else cls.get_total_count_for_sql(
|
||||
sql,
|
||||
query=query,
|
||||
user_context=user_context,
|
||||
)
|
||||
display_columns = cls._localize_asset_columns(raw_columns, query, sql, agent=agent)
|
||||
display_rows = cls._localize_asset_rows(raw_columns, raw_rows, query, sql, agent=agent)
|
||||
return display_columns, display_rows, resolved_total
|
||||
@@ -1753,7 +2076,13 @@ ORDER BY faj.faj02
|
||||
|
||||
# 2. Execute SQL
|
||||
stage_start = time.time()
|
||||
columns, rows = Text2SQLService.execute_sql(sql, query=query, agent=agent, limit=Text2SQLService._ASSET_CHAT_RESULT_LIMIT)
|
||||
columns, rows = Text2SQLService.execute_sql(
|
||||
sql,
|
||||
query=query,
|
||||
agent=agent,
|
||||
limit=Text2SQLService._ASSET_CHAT_RESULT_LIMIT,
|
||||
user_context=user_context,
|
||||
)
|
||||
execute_sql_ms = int((time.time() - stage_start) * 1000)
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
@@ -1794,8 +2123,22 @@ ORDER BY faj.faj02
|
||||
# 3. Format result
|
||||
yield f"data: {json.dumps({'event': 'message', 'answer': '📝 数据检索完成,正在生成最终业务报告...\n'})}\n\n"
|
||||
stage_start = time.time()
|
||||
result_text = Text2SQLService.format_result(columns, rows, sql, query, agent=agent)
|
||||
result_preview_payload = Text2SQLService.build_query_preview_payload(columns, rows, sql, query, agent=agent)
|
||||
result_text = Text2SQLService.format_result(
|
||||
columns,
|
||||
rows,
|
||||
sql,
|
||||
query,
|
||||
agent=agent,
|
||||
user_context=user_context,
|
||||
)
|
||||
result_preview_payload = Text2SQLService.build_query_preview_payload(
|
||||
columns,
|
||||
rows,
|
||||
sql,
|
||||
query,
|
||||
agent=agent,
|
||||
user_context=user_context,
|
||||
)
|
||||
format_result_ms = int((time.time() - stage_start) * 1000)
|
||||
latency = int((time.time() - start_time) * 1000)
|
||||
if current_app:
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
"""
|
||||
backend/migrations/versions/c6d7e8f9a0b1_add_faq_kb_stale_fields.py
|
||||
|
||||
用途:为 quick_questions 增加 KB 关联与待复审(stale)字段,支持方案 B 失效标记。
|
||||
依赖:alembic.op、sqlalchemy。
|
||||
逻辑:KB sync 成功后按 source_kb_document_ids / retriever_resources 标记 FAQ 待复审。
|
||||
"""
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = "c6d7e8f9a0b1"
|
||||
down_revision = "c5d6e7f8a9b0"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
op.add_column(
|
||||
"quick_questions",
|
||||
sa.Column("source_kb_document_ids", sa.JSON(), nullable=True),
|
||||
)
|
||||
op.add_column(
|
||||
"quick_questions",
|
||||
sa.Column("stale_at", sa.DateTime(), nullable=True),
|
||||
)
|
||||
op.add_column(
|
||||
"quick_questions",
|
||||
sa.Column("stale_reason", sa.String(length=64), nullable=True),
|
||||
)
|
||||
op.add_column(
|
||||
"quick_questions",
|
||||
sa.Column("stale_kb_document_id", sa.Integer(), nullable=True),
|
||||
)
|
||||
op.create_foreign_key(
|
||||
"fk_quick_questions_stale_kb_document_id",
|
||||
"quick_questions",
|
||||
"kb_documents",
|
||||
["stale_kb_document_id"],
|
||||
["id"],
|
||||
)
|
||||
op.create_index(
|
||||
"ix_quick_questions_stale_at",
|
||||
"quick_questions",
|
||||
["stale_at"],
|
||||
)
|
||||
|
||||
|
||||
def downgrade():
|
||||
op.drop_index("ix_quick_questions_stale_at", table_name="quick_questions")
|
||||
op.drop_constraint(
|
||||
"fk_quick_questions_stale_kb_document_id",
|
||||
"quick_questions",
|
||||
type_="foreignkey",
|
||||
)
|
||||
op.drop_column("quick_questions", "stale_kb_document_id")
|
||||
op.drop_column("quick_questions", "stale_reason")
|
||||
op.drop_column("quick_questions", "stale_at")
|
||||
op.drop_column("quick_questions", "source_kb_document_ids")
|
||||
@@ -267,6 +267,11 @@ def test_reports(client, admin_headers):
|
||||
assert 'total' in data
|
||||
assert 'by_user' in data
|
||||
assert 'by_agent' in data
|
||||
assert 'user_total' in data
|
||||
assert 'user_page' in data
|
||||
assert 'user_page_size' in data
|
||||
assert 'user_pages' in data
|
||||
assert 'user_top_limit' in data
|
||||
|
||||
response = client.get('/api/admin/reports/feedback', headers=admin_headers)
|
||||
assert response.status_code == 200
|
||||
|
||||
@@ -127,5 +127,96 @@ def test_update_chat_log_tokens_backfills_after_message_end(app):
|
||||
assert updated is True
|
||||
assert db.session.get(ChatLog, chat_log_id).tokens_used == 3068
|
||||
|
||||
# 不应被更小的值覆盖
|
||||
|
||||
def test_collect_knowledge_retrieval_from_node_finished():
|
||||
"""Chatflow:知识检索来源应从 node_finished.outputs.result 提取。"""
|
||||
retriever_resources: list = []
|
||||
event_data = {
|
||||
'event': 'node_finished',
|
||||
'data': {
|
||||
'node_type': 'knowledge-retrieval',
|
||||
'status': 'succeeded',
|
||||
'outputs': {
|
||||
'result': [
|
||||
{
|
||||
'metadata': {
|
||||
'dataset_id': 'ac0cf595-ca91-4f48-a0d1-0d31544c4136',
|
||||
'dataset_name': '4.人事规章',
|
||||
'document_id': '94b7246a-4daa-4dff-bdef-01510848f985',
|
||||
'document_name': '员工入职须4',
|
||||
'segment_id': '9d10e131-bf02-4add-8ef1-d3098a2ab7a4',
|
||||
'score': 0.8577696681022644,
|
||||
},
|
||||
'title': '员工入职须4',
|
||||
'files': None,
|
||||
'content': '员工入职须知4\n2.上班时间',
|
||||
},
|
||||
{
|
||||
'metadata': {
|
||||
'dataset_id': 'ac0cf595-ca91-4f48-a0d1-0d31544c4136',
|
||||
'document_id': '97eab330-d658-4f9e-aa7f-a24423234ee5',
|
||||
'document_name': '考勤-公司班次信息',
|
||||
},
|
||||
'title': '考勤-公司班次信息',
|
||||
'content': '考勤-公司班次信息',
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
DifyService._collect_knowledge_retrieval_from_node(retriever_resources, event_data)
|
||||
|
||||
assert len(retriever_resources) == 2
|
||||
assert retriever_resources[0]['document_id'] == '94b7246a-4daa-4dff-bdef-01510848f985'
|
||||
assert retriever_resources[0]['document_name'] == '员工入职须4'
|
||||
assert retriever_resources[0]['dataset_id'] == 'ac0cf595-ca91-4f48-a0d1-0d31544c4136'
|
||||
assert retriever_resources[1]['document_id'] == '97eab330-d658-4f9e-aa7f-a24423234ee5'
|
||||
|
||||
|
||||
def test_attach_retriever_resources_to_workflow_finished_event():
|
||||
"""workflow_finished 下发前应携带 retriever_resources 供前端展示源文件。"""
|
||||
resources = [
|
||||
{
|
||||
'dataset_id': 'ds-1',
|
||||
'document_id': 'doc-1',
|
||||
'document_name': '员工入职须知.pdf',
|
||||
'content': '上班时间 8:00',
|
||||
},
|
||||
]
|
||||
event_data = {'event': 'workflow_finished', 'metadata': {}}
|
||||
|
||||
DifyService._attach_retriever_resources_to_event(event_data, resources)
|
||||
|
||||
assert len(event_data['retriever_resources']) == 1
|
||||
assert event_data['retriever_resources'][0]['document_name'] == '员工入职须知.pdf'
|
||||
assert event_data['metadata']['retriever_resources'][0]['document_id'] == 'doc-1'
|
||||
|
||||
|
||||
def test_update_chat_log_tokens_does_not_decrease(app):
|
||||
"""已写入更大 token 后,不应被更小的值覆盖。"""
|
||||
with app.app_context():
|
||||
user = User(username='u3', role='user', email='u3@example.com')
|
||||
agent = Agent(name='wf_agent3', dify_app_id='wf-3')
|
||||
db.session.add_all([user, agent])
|
||||
db.session.commit()
|
||||
|
||||
first = DifyService._persist_stream_chat_record(
|
||||
data={'event': 'message_end', 'conversation_id': 'conv-wf-3', 'metadata': {}},
|
||||
event_name='message_end',
|
||||
request_id='req-wf-3',
|
||||
user_id=user.id,
|
||||
agent=agent,
|
||||
session_id='sess-wf-3',
|
||||
hxops_turn_id=None,
|
||||
normalized_conversation_id='conv-wf-3',
|
||||
query='test',
|
||||
answer_text='answer',
|
||||
latency=1000,
|
||||
retriever_resources=[],
|
||||
attribution_parts=[],
|
||||
)
|
||||
chat_log_id = first['chat_log_id']
|
||||
DifyService._update_chat_log_tokens(chat_log_id, 500)
|
||||
assert DifyService._update_chat_log_tokens(chat_log_id, 100) is False
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
"""
|
||||
backend/tests/test_faq_kb_invalidation.py
|
||||
|
||||
用途:FAQ 与 KB 文档关联解析及失效标记单元测试。
|
||||
"""
|
||||
from app.services.faq_kb_invalidation import (
|
||||
_faq_links_kb_document,
|
||||
extract_dify_id_pairs,
|
||||
merge_source_kb_document_ids,
|
||||
)
|
||||
from app.models import QuickQuestion
|
||||
|
||||
|
||||
def test_extract_dify_id_pairs_from_retriever_resources():
|
||||
resources = [
|
||||
{'dataset_id': 'ds-1', 'document_id': 'doc-1'},
|
||||
{'metadata': {'dify_dataset_id': 'ds-2', 'remote_document_id': 'doc-2'}},
|
||||
]
|
||||
pairs = extract_dify_id_pairs(resources)
|
||||
assert ('ds-1', 'doc-1') in pairs
|
||||
assert ('ds-2', 'doc-2') in pairs
|
||||
|
||||
|
||||
def test_faq_links_kb_document_by_source_ids():
|
||||
qq = QuickQuestion(
|
||||
user_id=None,
|
||||
agent_id=1,
|
||||
title='t',
|
||||
question='q',
|
||||
source_kb_document_ids=[10, 20],
|
||||
)
|
||||
assert _faq_links_kb_document(qq, 10, None, None) is True
|
||||
assert _faq_links_kb_document(qq, 99, None, None) is False
|
||||
|
||||
|
||||
def test_faq_links_kb_document_by_retriever_resources():
|
||||
qq = QuickQuestion(
|
||||
user_id=None,
|
||||
agent_id=1,
|
||||
title='t',
|
||||
question='q',
|
||||
retriever_resources=[{'dataset_id': 'ds-a', 'document_id': 'remote-a'}],
|
||||
)
|
||||
assert _faq_links_kb_document(qq, 0, 'ds-a', 'remote-a') is True
|
||||
assert _faq_links_kb_document(qq, 0, 'ds-b', 'remote-a') is False
|
||||
|
||||
|
||||
def test_merge_source_kb_document_ids():
|
||||
merged = merge_source_kb_document_ids([1], None)
|
||||
assert merged == [1]
|
||||
@@ -0,0 +1,113 @@
|
||||
"""
|
||||
backend/tests/test_fixed_assets_snapshot.py
|
||||
|
||||
用途:验证固定资产快照查询服务的核心过滤行为。
|
||||
依赖:pytest、Flask app fixture、FixedAssetsSnapshotService。
|
||||
逻辑关系:覆盖“资产名称+规格型号组合查询”和“本人名下资产查询”两个高频场景。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from app.services.fixed_assets_snapshot import FixedAssetsSnapshotService
|
||||
|
||||
|
||||
def _seed_latest_snapshot(root: Path) -> None:
|
||||
"""写入一份最小可用的 latest 快照,供查询服务读取。"""
|
||||
rows = [
|
||||
{
|
||||
"资产编号": "A0827011",
|
||||
"资产名称": "线切割机",
|
||||
"资产名称2": "",
|
||||
"规格型号": "DK7732",
|
||||
"保管人工号": "E1001",
|
||||
"保管人姓名": "张三",
|
||||
"保管部门编号": "D01",
|
||||
"保管部门名称": "制造部",
|
||||
"存放位置名称": "一厂机加区",
|
||||
"资产状态": "折旧中",
|
||||
"资产状态代码": "2",
|
||||
"预留残值": "1000",
|
||||
"供应厂商": "华东设备",
|
||||
"资产性质": "有形资产",
|
||||
"资产性质代码": "1",
|
||||
"本币单价": "60000",
|
||||
"数量": "1",
|
||||
"计量单位": "台",
|
||||
"取得日期": "2024-01-01 00:00:00",
|
||||
"入账日期": "2024-01-10 00:00:00",
|
||||
"营运中心代码": "HXJM",
|
||||
"站点代码": "JM",
|
||||
"备注": "资产编号:A0827011 | 资产名称:线切割机 | 规格型号:DK7732 | 保管人姓名:张三 | 保管部门名称:制造部 | 存放位置名称:一厂机加区 | 资产状态:折旧中 | 供应厂商:华东设备 | 资产性质:有形资产",
|
||||
"备注标准化": "资产编号A0827011资产名称线切割机规格型号DK7732保管人姓名张三保管部门名称制造部存放位置名称一厂机加区资产状态折旧中供应厂商华东设备资产性质有形资产",
|
||||
},
|
||||
{
|
||||
"资产编号": "A0827012",
|
||||
"资产名称": "400吨冲床",
|
||||
"资产名称2": "",
|
||||
"规格型号": "JH21-400",
|
||||
"保管人工号": "E1002",
|
||||
"保管人姓名": "李四",
|
||||
"保管部门编号": "D02",
|
||||
"保管部门名称": "冲压部",
|
||||
"存放位置名称": "二厂冲压区",
|
||||
"资产状态": "折旧中",
|
||||
"资产状态代码": "2",
|
||||
"预留残值": "2000",
|
||||
"供应厂商": "华南设备",
|
||||
"资产性质": "有形资产",
|
||||
"资产性质代码": "1",
|
||||
"本币单价": "200000",
|
||||
"数量": "1",
|
||||
"计量单位": "台",
|
||||
"取得日期": "2023-01-01 00:00:00",
|
||||
"入账日期": "2023-01-10 00:00:00",
|
||||
"营运中心代码": "HTT",
|
||||
"站点代码": "TT",
|
||||
"备注": "资产编号:A0827012 | 资产名称:400吨冲床 | 规格型号:JH21-400 | 保管人姓名:李四 | 保管部门名称:冲压部 | 存放位置名称:二厂冲压区 | 资产状态:折旧中 | 供应厂商:华南设备 | 资产性质:有形资产",
|
||||
"备注标准化": "资产编号A0827012资产名称400吨冲床规格型号JH21400保管人姓名李四保管部门名称冲压部存放位置名称二厂冲压区资产状态折旧中供应厂商华南设备资产性质有形资产",
|
||||
},
|
||||
]
|
||||
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
latest_dir = root / "latest"
|
||||
latest_dir.mkdir(parents=True, exist_ok=True)
|
||||
FixedAssetsSnapshotService._write_snapshot_db(
|
||||
latest_dir / "FixedAssets_latest.db",
|
||||
rows,
|
||||
version="20260622_030000",
|
||||
snapshot_date="2026-06-22",
|
||||
)
|
||||
|
||||
|
||||
def test_query_assets_supports_name_and_spec_combo(app, tmp_path):
|
||||
app.config["FIXED_ASSETS_STORAGE_ROOT"] = str(tmp_path / "fixed_assets")
|
||||
with app.app_context():
|
||||
_seed_latest_snapshot(tmp_path / "fixed_assets")
|
||||
|
||||
columns, rows, total = FixedAssetsSnapshotService.query_assets("查询线切割机 规格型号 DK7732")
|
||||
|
||||
# 断言:组合查询应命中同一台设备,且返回预期中文列头。
|
||||
assert columns[:3] == ["资产编号", "资产名称", "规格型号"]
|
||||
assert total == 1
|
||||
assert rows[0][0] == "A0827011"
|
||||
assert rows[0][1] == "线切割机"
|
||||
assert rows[0][2] == "DK7732"
|
||||
|
||||
|
||||
def test_query_assets_supports_self_scope(app, tmp_path):
|
||||
app.config["FIXED_ASSETS_STORAGE_ROOT"] = str(tmp_path / "fixed_assets")
|
||||
with app.app_context():
|
||||
_seed_latest_snapshot(tmp_path / "fixed_assets")
|
||||
|
||||
columns, rows, total = FixedAssetsSnapshotService.query_assets(
|
||||
"查询我名下固定资产",
|
||||
user_context={"employee_id": "E1001", "real_name": "张三", "username": "zhangsan"},
|
||||
)
|
||||
|
||||
# 断言:本人查询必须按当前用户身份过滤,不能返回其他人的资产。
|
||||
assert columns[0] == "资产编号"
|
||||
assert total == 1
|
||||
assert len(rows) == 1
|
||||
assert rows[0][0] == "A0827011"
|
||||
assert rows[0][3] == "张三"
|
||||
@@ -1,10 +1,9 @@
|
||||
"""
|
||||
backend/tests/test_hot_faq_aggregator.py
|
||||
|
||||
测试热点 FAQ 离线聚合的核心规则:问句归一化、答案聚类与代表答案选取。
|
||||
测试热点 FAQ 离线聚合的核心规则:问句归一化、代表答案选取。
|
||||
"""
|
||||
from datetime import datetime
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app.services.faq_text_utils import normalize_faq_query
|
||||
from app.services.hot_faq_aggregator import HotFaqAggregator, _LogRow
|
||||
@@ -15,15 +14,19 @@ def test_normalize_faq_query_strips_punctuation_and_space():
|
||||
assert normalize_faq_query('公司几点上班?') == normalize_faq_query('公司 几点上班')
|
||||
|
||||
|
||||
def test_answer_cluster_merges_similar_answers():
|
||||
"""相似度≥阈值的答案应归入同一簇。"""
|
||||
rows = [
|
||||
_LogRow(1, 1, 1, 'q', '工作日8:30到17:30', 100, 10, datetime.utcnow()),
|
||||
_LogRow(2, 2, 1, 'q', '工作日 8:30 到 17:30', 100, 10, datetime.utcnow()),
|
||||
]
|
||||
clusters = HotFaqAggregator._cluster_answers(rows)
|
||||
assert len(clusters) == 1
|
||||
assert len(clusters[0]['rows']) == 2
|
||||
def test_build_candidate_accepts_divergent_answers_when_clustering_disabled(app, monkeypatch):
|
||||
"""答案聚类关闭时,即使答案分歧较大也应生成热点候选。"""
|
||||
monkeypatch.setenv('FAQ_HOT_ANSWER_DOMINANCE', '0.6')
|
||||
with app.app_context():
|
||||
now = datetime.utcnow()
|
||||
rows = [
|
||||
_LogRow(i, i, 1, '上班时间', f'answer variant {i % 3}', 200, 100, now)
|
||||
for i in range(6)
|
||||
]
|
||||
candidate, reason = HotFaqAggregator._build_candidate(1, 'Agent', '上班时间', rows)
|
||||
assert candidate is not None
|
||||
assert reason is None
|
||||
assert candidate.ask_count_7d == 6
|
||||
|
||||
|
||||
def test_pick_representative_prefers_good_feedback():
|
||||
@@ -37,17 +40,3 @@ def test_pick_representative_prefers_good_feedback():
|
||||
assert picked is not None
|
||||
assert picked.chat_log_id == 2
|
||||
assert picked.answer == 'answer B'
|
||||
|
||||
|
||||
def test_build_candidate_rejects_divergent_answers(app, monkeypatch):
|
||||
"""答案分歧过大时应跳过该热点组。"""
|
||||
monkeypatch.setenv('FAQ_HOT_ANSWER_DOMINANCE', '0.6')
|
||||
with app.app_context():
|
||||
now = datetime.utcnow()
|
||||
rows = [
|
||||
_LogRow(i, i, 1, '上班时间', f'answer variant {i % 3}', 200, 100, now)
|
||||
for i in range(6)
|
||||
]
|
||||
candidate, reason = HotFaqAggregator._build_candidate(1, 'Agent', '上班时间', rows)
|
||||
assert candidate is None
|
||||
assert reason and reason.startswith('answer_divergence')
|
||||
@@ -1,7 +1,21 @@
|
||||
import pytest
|
||||
from app.models import User
|
||||
from app.models import User, Agent
|
||||
from app import db
|
||||
|
||||
def _error_message(response):
|
||||
body = response.get_json() or {}
|
||||
error = body.get('error')
|
||||
if isinstance(error, dict):
|
||||
return str(error.get('message') or '')
|
||||
return str(error or '')
|
||||
|
||||
def _error_code(response):
|
||||
body = response.get_json() or {}
|
||||
error = body.get('error')
|
||||
if isinstance(error, dict):
|
||||
return str(error.get('code') or '')
|
||||
return ''
|
||||
|
||||
def test_register_fields_validation(client):
|
||||
"""
|
||||
Test user registration field validation
|
||||
@@ -40,7 +54,7 @@ def test_register_fields_validation(client):
|
||||
}
|
||||
response = client.post('/api/user/register', json=dup_user)
|
||||
assert response.status_code == 400
|
||||
assert "Employee ID already exists" in response.json['error']
|
||||
assert "Employee ID already exists" in _error_message(response)
|
||||
|
||||
def test_admin_duplicate_employee_id(client, admin_headers):
|
||||
"""
|
||||
@@ -68,8 +82,8 @@ def test_admin_duplicate_employee_id(client, admin_headers):
|
||||
"phone_number": "13800000012"
|
||||
}
|
||||
response = client.post('/api/admin/users', json=u2, headers=admin_headers)
|
||||
assert response.status_code == 400
|
||||
assert "Employee ID already exists" in response.json['error']
|
||||
assert response.status_code == 409
|
||||
assert "Employee ID already exists" in _error_message(response)
|
||||
|
||||
# 3. Update user to duplicate ID
|
||||
# Create u3 with valid ID
|
||||
@@ -86,5 +100,44 @@ def test_admin_duplicate_employee_id(client, admin_headers):
|
||||
|
||||
# Update u3 to ADM001 (which exists)
|
||||
res = client.put(f'/api/admin/users/{u3_id}', json={"employee_id": "ADM001"}, headers=admin_headers)
|
||||
assert res.status_code == 400
|
||||
assert "Employee ID already exists" in res.json['error']
|
||||
assert res.status_code == 409
|
||||
assert "Employee ID already exists" in _error_message(res)
|
||||
assert _error_code(res) == 'USER.EMPLOYEE_ID_EXISTS'
|
||||
|
||||
def test_admin_duplicate_phone_on_update_with_agent_ids(client, admin_headers):
|
||||
"""
|
||||
编辑用户时若手机号重复且同时提交 agent_ids,应在 autoflush 前返回冲突而非 500。
|
||||
"""
|
||||
existing = {
|
||||
"username": "phone_owner",
|
||||
"password": "pwd",
|
||||
"email": "phone_owner@e.com",
|
||||
"real_name": "Phone Owner",
|
||||
"employee_id": "PHN001",
|
||||
"phone_number": "123456",
|
||||
}
|
||||
target = {
|
||||
"username": "phone_target",
|
||||
"password": "pwd",
|
||||
"email": "phone_target@e.com",
|
||||
"real_name": "Phone Target",
|
||||
"employee_id": "PHN002",
|
||||
"phone_number": "13800009999",
|
||||
}
|
||||
assert client.post('/api/admin/users', json=existing, headers=admin_headers).status_code == 201
|
||||
target_res = client.post('/api/admin/users', json=target, headers=admin_headers)
|
||||
assert target_res.status_code == 201
|
||||
target_id = target_res.json['id']
|
||||
|
||||
agent = Agent(name='Dup Phone Agent', dify_app_id='dup-phone-agent', type='chat')
|
||||
db.session.add(agent)
|
||||
db.session.commit()
|
||||
|
||||
res = client.put(
|
||||
f'/api/admin/users/{target_id}',
|
||||
json={'phone_number': '123456', 'agent_ids': [agent.id]},
|
||||
headers=admin_headers,
|
||||
)
|
||||
assert res.status_code == 409
|
||||
assert _error_code(res) == 'USER.PHONE_EXISTS'
|
||||
assert "Phone number already exists" in _error_message(res)
|
||||
Reference in new issue
Block a user