添加意见反馈
This commit is contained in:
1 parent
2bd27ed70d
commit
6b2ab65436
16 files changed
+853
-37
No files matched your search
@@ -5,7 +5,7 @@ backend/app/api/admin.py
|
||||
逻辑关系:提供 Agent 配置管理、用户与权限管理接口,供前端 Admin 控制台使用
|
||||
"""
|
||||
from flask import Blueprint, request, jsonify, current_app
|
||||
from app.models import Agent, User, PermissionRequest, ChatLog, Feedback, Department, UserFavoriteAgent, UserDefaultAgent, QuickQuestion, UserHomepageConfig, LoginAudit, WecomNotifyAudit
|
||||
from app.models import Agent, User, PermissionRequest, ChatLog, Feedback, GeneralFeedback, Department, UserFavoriteAgent, UserDefaultAgent, QuickQuestion, UserHomepageConfig, LoginAudit, WecomNotifyAudit
|
||||
from app.decorators import require_admin
|
||||
from app.config import Config
|
||||
from app import db
|
||||
@@ -829,6 +829,62 @@ def feedback_report():
|
||||
'distribution': [{'score': s, 'count': c} for s, c in dist]
|
||||
})
|
||||
|
||||
@admin_bp.route('/reports/general-feedbacks', methods=['GET'])
|
||||
@require_admin
|
||||
def list_general_feedbacks_report():
|
||||
"""
|
||||
List rows from general_feedbacks for report page display.
|
||||
Supports simple fuzzy filters by column name and optional limit.
|
||||
"""
|
||||
query = db.session.query(GeneralFeedback)
|
||||
|
||||
reserved = {'limit', 'offset', 'page', 'page_size'}
|
||||
for key, value in request.args.items():
|
||||
if key in reserved:
|
||||
continue
|
||||
if not value or not hasattr(GeneralFeedback, key):
|
||||
continue
|
||||
col = getattr(GeneralFeedback, key)
|
||||
query = query.filter(col.cast(db.String).ilike(f"%{value}%"))
|
||||
|
||||
query = query.order_by(desc(GeneralFeedback.created_at), desc(GeneralFeedback.id))
|
||||
|
||||
try:
|
||||
limit = int(request.args.get('limit', 200))
|
||||
except (TypeError, ValueError):
|
||||
limit = 200
|
||||
limit = max(1, min(limit, 1000))
|
||||
|
||||
items = query.limit(limit).all()
|
||||
rows = []
|
||||
for item in items:
|
||||
row = {}
|
||||
for col in item.__table__.columns:
|
||||
val = getattr(item, col.name)
|
||||
if isinstance(val, datetime):
|
||||
val = val.isoformat()
|
||||
row[col.name] = val
|
||||
rows.append(row)
|
||||
return jsonify(rows)
|
||||
|
||||
|
||||
@admin_bp.route('/reports/general-feedbacks/count', methods=['GET'])
|
||||
@require_admin
|
||||
def count_general_feedbacks_report():
|
||||
query = db.session.query(GeneralFeedback)
|
||||
|
||||
reserved = {'limit', 'offset', 'page', 'page_size'}
|
||||
for key, value in request.args.items():
|
||||
if key in reserved:
|
||||
continue
|
||||
if not value or not hasattr(GeneralFeedback, key):
|
||||
continue
|
||||
col = getattr(GeneralFeedback, key)
|
||||
query = query.filter(col.cast(db.String).ilike(f"%{value}%"))
|
||||
|
||||
total = query.count()
|
||||
return jsonify({'table': 'general_feedbacks', 'total': int(total)})
|
||||
|
||||
|
||||
# --- Database ---
|
||||
@admin_bp.route('/database/<table>', methods=['GET'])
|
||||
|
||||
@@ -155,6 +155,7 @@ def get_chat_messages():
|
||||
messages.append({
|
||||
'role': 'assistant',
|
||||
'content': log.answer,
|
||||
'chat_log_id': log.id,
|
||||
'retriever_resources': log.retriever_resources or [],
|
||||
'attribution_parts': log.attribution_parts or []
|
||||
})
|
||||
|
||||
+63
-1
@@ -1,6 +1,6 @@
|
||||
from flask import Blueprint, request, jsonify, current_app
|
||||
from app import db
|
||||
from app.models import User, Agent, QuickQuestion, UserFavoriteAgent, UserDefaultAgent, UserHomepageConfig, Announcement, LoginAudit, WecomCallbackAudit
|
||||
from app.models import User, Agent, QuickQuestion, UserFavoriteAgent, UserDefaultAgent, UserHomepageConfig, Announcement, LoginAudit, WecomCallbackAudit, GeneralFeedback, ChatLog
|
||||
from app.services.wecom_notify import mark_wecom_message_opened, send_wecom_event_message
|
||||
from app.services.wecom_crypto import sha1_hex, decrypt_wecom_aes, extract_encrypt_field
|
||||
from sqlalchemy.exc import IntegrityError, OperationalError
|
||||
@@ -1147,6 +1147,68 @@ def unbind_wecom_self():
|
||||
db.session.commit()
|
||||
return jsonify({'status': 'ok', 'message': 'WeCom account unbound'})
|
||||
|
||||
@user_bp.route('/feedback', methods=['POST'])
|
||||
def submit_general_feedback():
|
||||
"""
|
||||
通用意见反馈接口(与 /api/chat/feedback 的对话评分接口不同
|
||||
"""
|
||||
user = _get_current_user()
|
||||
if not user:
|
||||
return jsonify({'error': 'Unauthorized'}), 401
|
||||
|
||||
data = request.get_json() or {}
|
||||
feedback_type = _clean_str(data.get('feedback_type'))
|
||||
feedback_module = _clean_str(data.get('feedback_module'))
|
||||
content = _clean_str(data.get('content'))
|
||||
source_page = _clean_str(data.get('source_page'))
|
||||
|
||||
raw_chat_log_id = data.get('chat_log_id')
|
||||
chat_log_id = None
|
||||
if raw_chat_log_id not in (None, ''):
|
||||
try:
|
||||
chat_log_id = int(raw_chat_log_id)
|
||||
except (TypeError, ValueError):
|
||||
return jsonify({'error': 'chat_log_id must be an integer'}), 400
|
||||
if chat_log_id <= 0:
|
||||
return jsonify({'error': 'chat_log_id must be a positive integer'}), 400
|
||||
|
||||
if not feedback_type:
|
||||
return jsonify({'error': 'feedback_type is required'}), 400
|
||||
if not feedback_module:
|
||||
return jsonify({'error': 'feedback_module is required'}), 400
|
||||
if len(feedback_type) > 32:
|
||||
return jsonify({'error': 'feedback_type is too long'}), 400
|
||||
if len(feedback_module) > 32:
|
||||
return jsonify({'error': 'feedback_module is too long'}), 400
|
||||
if not content:
|
||||
return jsonify({'error': 'content is required'}), 400
|
||||
if len(content) > 2000:
|
||||
return jsonify({'error': 'content is too long'}), 400
|
||||
|
||||
if source_page != 'chat':
|
||||
chat_log_id = None
|
||||
|
||||
if chat_log_id is not None:
|
||||
chat_log = db.session.get(ChatLog, chat_log_id)
|
||||
if not chat_log:
|
||||
return jsonify({'error': 'chat_log_id not found'}), 400
|
||||
if chat_log.user_id != user.id:
|
||||
return jsonify({'error': 'chat_log_id is not owned by current user'}), 403
|
||||
|
||||
row = GeneralFeedback(
|
||||
user_id=user.id,
|
||||
username=user.username,
|
||||
feedback_type=feedback_type,
|
||||
feedback_module=feedback_module,
|
||||
content=content,
|
||||
source_page=source_page,
|
||||
chat_log_id=chat_log_id,
|
||||
)
|
||||
db.session.add(row)
|
||||
db.session.commit()
|
||||
|
||||
return jsonify({'status': 'ok', 'id': row.id})
|
||||
|
||||
@user_bp.route('/home', methods=['GET'])
|
||||
def home():
|
||||
"""
|
||||
|
||||
@@ -72,8 +72,8 @@ class DevelopmentConfig(Config):
|
||||
DEBUG = True
|
||||
SQLALCHEMY_DATABASE_URI = os.getenv(
|
||||
'DATABASE_URL',
|
||||
# 'postgresql://postgres:123456@8.152.207.171:5432/hxops_db',
|
||||
'postgresql://postgres:difyai123456@localhost:5432/hxops_db',
|
||||
'postgresql://postgres:123456@8.152.207.171:5432/hxops_db',
|
||||
#'postgresql://postgres:difyai123456@localhost:5432/hxops_db',
|
||||
)
|
||||
|
||||
|
||||
|
||||
+18
-1
@@ -1,4 +1,3 @@
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Optional, List
|
||||
from sqlalchemy import String, Text, Integer, ForeignKey, JSON, DateTime, Index
|
||||
@@ -217,6 +216,23 @@ class Feedback(Base):
|
||||
|
||||
chat_log: Mapped["ChatLog"] = relationship(back_populates="feedback")
|
||||
|
||||
class GeneralFeedback(Base):
|
||||
"""
|
||||
通用意见反馈表
|
||||
用于存储 Workspace/Chat 页面提交的通用意见反馈
|
||||
"""
|
||||
__tablename__ = 'general_feedbacks'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), index=True)
|
||||
chat_log_id: Mapped[Optional[int]] = mapped_column(ForeignKey('chat_logs.id'), nullable=True, index=True)
|
||||
username: Mapped[str] = mapped_column(String(50), nullable=False)
|
||||
feedback_type: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
feedback_module: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
content: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
source_page: Mapped[Optional[str]] = mapped_column(String(32))
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
|
||||
class PermissionRequest(Base):
|
||||
"""
|
||||
权限申请表
|
||||
@@ -342,3 +358,4 @@ class WecomCallbackAudit(Base):
|
||||
msg_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
|
||||
error_message: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
|
||||
@@ -24,7 +24,7 @@ chat.py (/api/chat/completions)
|
||||
"""
|
||||
import json
|
||||
import time
|
||||
from typing import Any, List
|
||||
from typing import Any, List, Optional
|
||||
|
||||
import requests
|
||||
from flask import current_app
|
||||
@@ -153,7 +153,7 @@ class DifyService:
|
||||
usage = metadata.get('usage', {}) or {}
|
||||
|
||||
with current_app.app_context():
|
||||
DifyService._log_chat(
|
||||
chat_log_id = DifyService._log_chat(
|
||||
user_id=user_id,
|
||||
agent_id=agent.id,
|
||||
conversation_id=data.get('conversation_id') or conversation_id,
|
||||
@@ -164,6 +164,8 @@ class DifyService:
|
||||
retriever_resources=retriever_resources,
|
||||
attribution_parts=attribution_parts,
|
||||
)
|
||||
if chat_log_id:
|
||||
data['chat_log_id'] = chat_log_id
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[chat-stream] message_end logged conversation_id=%s answer_len=%s resources=%s attribution=%s latency_ms=%s",
|
||||
@@ -195,7 +197,7 @@ class DifyService:
|
||||
latency,
|
||||
retriever_resources=None,
|
||||
attribution_parts=None,
|
||||
):
|
||||
) -> Optional[int]:
|
||||
"""
|
||||
把最终问答和元数据写入 ChatLog
|
||||
Persist one chat record into ChatLog table.
|
||||
@@ -223,10 +225,14 @@ class DifyService:
|
||||
)
|
||||
db.session.add(chat_log)
|
||||
db.session.commit()
|
||||
return chat_log.id
|
||||
except Exception as e:
|
||||
if current_app:
|
||||
current_app.logger.error(f'Failed to log chat: {e}')
|
||||
db.session.rollback()
|
||||
return None
|
||||
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def _normalize_resources(resources):
|
||||
|
||||
Reference in new issue
Block a user