Compare commits
14
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d4c30b5825 | ||
|
|
836ddea84d | ||
|
|
34ad40778b | ||
|
|
e8ad4cc743 | ||
|
|
37b743d5d3 | ||
|
|
ade440d004 | ||
|
|
3f025fbb9b | ||
|
|
ed18907e95 | ||
|
|
a91f26f753 | ||
|
|
b64ed9b792 | ||
|
|
6eb4c76beb | ||
|
|
29315cab20 | ||
|
|
b31e887b2a | ||
|
|
d094d8eb83 |
No files matched your search
@@ -5,7 +5,9 @@ backend/app/api/admin/reports.py
|
|||||||
依赖:admin.blueprint、services/admin/report_service。
|
依赖:admin.blueprint、services/admin/report_service。
|
||||||
逻辑:/reports/usage、/reports/applications、feedback 与 general-feedbacks 路由。
|
逻辑:/reports/usage、/reports/applications、feedback 与 general-feedbacks 路由。
|
||||||
"""
|
"""
|
||||||
from flask import jsonify, request
|
from urllib.parse import quote
|
||||||
|
|
||||||
|
from flask import Response, jsonify, request
|
||||||
|
|
||||||
from app.api.admin.blueprint import admin_bp
|
from app.api.admin.blueprint import admin_bp
|
||||||
from app.core.decorators import require_admin
|
from app.core.decorators import require_admin
|
||||||
@@ -134,3 +136,15 @@ def issue_analysis():
|
|||||||
def close_general_feedback(feedback_id: int):
|
def close_general_feedback(feedback_id: int):
|
||||||
"""将一条意见反馈标记为已关闭(status='closed')。"""
|
"""将一条意见反馈标记为已关闭(status='closed')。"""
|
||||||
return jsonify(report_service.mark_general_feedback_closed(feedback_id))
|
return jsonify(report_service.mark_general_feedback_closed(feedback_id))
|
||||||
|
|
||||||
|
|
||||||
|
@admin_bp.route('/reports/general-feedbacks/<int:feedback_id>/images/<int:image_id>/raw', methods=['GET'])
|
||||||
|
@require_admin
|
||||||
|
def general_feedback_image_raw(feedback_id: int, image_id: int):
|
||||||
|
"""代理输出意见反馈截图字节流(inline 展示用)。"""
|
||||||
|
payload = report_service.get_general_feedback_image_payload(feedback_id, image_id)
|
||||||
|
resp = Response(payload['data'], mimetype=payload['mime_type'])
|
||||||
|
# [SECURITY] Content-Type 已按扩展名白名单收敛,仍禁浏览器嗅探,双保险防内联渲染为 HTML
|
||||||
|
resp.headers['X-Content-Type-Options'] = 'nosniff'
|
||||||
|
resp.headers['Content-Disposition'] = f"inline; filename*=UTF-8''{quote(payload['filename'])}"
|
||||||
|
return resp
|
||||||
@@ -7,9 +7,10 @@ backend/app/api/user/handlers.py
|
|||||||
"""
|
"""
|
||||||
from flask import Blueprint, request, jsonify, current_app
|
from flask import Blueprint, request, jsonify, current_app
|
||||||
from sqlalchemy import and_, or_
|
from sqlalchemy import and_, or_
|
||||||
from sqlalchemy.exc import DatabaseError, OperationalError
|
from sqlalchemy.exc import DatabaseError, IntegrityError, OperationalError
|
||||||
from app import db
|
from app import db
|
||||||
from app.models import User, Agent, QuickQuestion, UserFavoriteAgent, UserDefaultAgent, UserHomepageConfig, GeneralFeedback, ChatLog
|
from app.models import User, Agent, QuickQuestion, UserFavoriteAgent, UserDefaultAgent, UserHomepageConfig, GeneralFeedback, GeneralFeedbackImage, ChatLog
|
||||||
|
from app.services.file_assets.service import get_asset_for_user, mark_asset_referenced
|
||||||
from app.services.feedback_notify import send_feedback_group_notification
|
from app.services.feedback_notify import send_feedback_group_notification
|
||||||
from app.services.agent_category import serialize_agent_list_item, sort_agent_rows
|
from app.services.agent_category import serialize_agent_list_item, sort_agent_rows
|
||||||
from app.services.agent_registry.serialization import serialize_registry_fields
|
from app.services.agent_registry.serialization import serialize_registry_fields
|
||||||
@@ -32,6 +33,11 @@ from .auth import (
|
|||||||
)
|
)
|
||||||
user_bp = Blueprint('user', __name__)
|
user_bp = Blueprint('user', __name__)
|
||||||
|
|
||||||
|
# [CONST] 反馈附件图片上限与允许的图片扩展名(POST /feedback 的 image_asset_nos 校验用)
|
||||||
|
_FEEDBACK_MAX_IMAGES = 5
|
||||||
|
_FEEDBACK_IMAGE_EXTENSIONS = {'png', 'jpg', 'jpeg', 'webp'}
|
||||||
|
|
||||||
|
|
||||||
@user_bp.route('/wecom/deeplink-opened', methods=['POST'])
|
@user_bp.route('/wecom/deeplink-opened', methods=['POST'])
|
||||||
def mark_wecom_deeplink_opened():
|
def mark_wecom_deeplink_opened():
|
||||||
user = _get_current_user()
|
user = _get_current_user()
|
||||||
@@ -161,9 +167,46 @@ def submit_general_feedback():
|
|||||||
raise ValidationError('chat_log_id not found')
|
raise ValidationError('chat_log_id not found')
|
||||||
if chat_log.user_id != user.id:
|
if chat_log.user_id != user.id:
|
||||||
raise ForbiddenError('chat_log_id is not owned by current user')
|
raise ForbiddenError('chat_log_id is not owned by current user')
|
||||||
|
# [STEP 1] 解析并规整 image_asset_nos(可选参数):非 list 直接拒绝;元素转 str 去空白、保序去重;超上限整单拒绝
|
||||||
|
raw_asset_nos = data.get('image_asset_nos')
|
||||||
|
normalized_asset_nos: list[str] = []
|
||||||
|
if raw_asset_nos is not None:
|
||||||
|
if not isinstance(raw_asset_nos, list):
|
||||||
|
raise ValidationError(code='FEEDBACK.IMAGE_INVALID', message='image_asset_nos must be a list')
|
||||||
|
seen_asset_nos: set[str] = set()
|
||||||
|
for item in raw_asset_nos:
|
||||||
|
asset_no = str(item or '').strip()
|
||||||
|
if not asset_no or asset_no in seen_asset_nos:
|
||||||
|
continue
|
||||||
|
seen_asset_nos.add(asset_no)
|
||||||
|
normalized_asset_nos.append(asset_no)
|
||||||
|
if len(normalized_asset_nos) > _FEEDBACK_MAX_IMAGES:
|
||||||
|
raise ValidationError(code='FEEDBACK.IMAGE_TOO_MANY', message='最多附加 5 张图片')
|
||||||
|
# [STEP 2] 逐个校验资产归属与图片语义(任一失败整单拒绝,反馈与图片关联都不落库)
|
||||||
|
feedback_assets = []
|
||||||
|
for asset_no in normalized_asset_nos:
|
||||||
|
asset = get_asset_for_user(asset_no, user.id)
|
||||||
|
if asset.extension not in _FEEDBACK_IMAGE_EXTENSIONS:
|
||||||
|
raise ValidationError(code='FEEDBACK.IMAGE_INVALID', message='仅支持 png/jpg/jpeg/webp 图片')
|
||||||
|
if asset.upload_status != 'ready':
|
||||||
|
raise ValidationError(code='FEEDBACK.IMAGE_INVALID', message='图片尚未上传完成')
|
||||||
|
if asset.reference_count != 0 or asset.lifecycle_status != 'temporary':
|
||||||
|
raise ValidationError(code='FEEDBACK.IMAGE_INVALID', message='该文件已被使用')
|
||||||
|
feedback_assets.append(asset)
|
||||||
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)
|
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)
|
||||||
|
# [STEP 3] 落库:flush 拿反馈 id → 按枚举序写图片关联(sort_order=下标)→ 逐个标记资产被引用 → commit;
|
||||||
|
# IntegrityError 兜底并发双挂(asset_id 唯一约束),回滚整单并转业务错误
|
||||||
db.session.add(row)
|
db.session.add(row)
|
||||||
db.session.commit()
|
db.session.flush()
|
||||||
|
for idx, asset in enumerate(feedback_assets):
|
||||||
|
db.session.add(GeneralFeedbackImage(feedback_id=row.id, asset_id=asset.id, sort_order=idx))
|
||||||
|
mark_asset_referenced(asset)
|
||||||
|
try:
|
||||||
|
db.session.commit()
|
||||||
|
except IntegrityError:
|
||||||
|
db.session.rollback()
|
||||||
|
raise ValidationError(code='FEEDBACK.IMAGE_INVALID', message='图片已被使用,请重新添加')
|
||||||
|
# [STEP 4] 通知与返回不变:提交成功后推送企微群通知(失败不影响提交结果),返回旧契约 JSON
|
||||||
notify_result = send_feedback_group_notification(row, user)
|
notify_result = send_feedback_group_notification(row, user)
|
||||||
if notify_result.get('ok'):
|
if notify_result.get('ok'):
|
||||||
current_app.logger.info('[feedback] group notification sent feedback_id=%s', row.id)
|
current_app.logger.info('[feedback] group notification sent feedback_id=%s', row.id)
|
||||||
|
|||||||
@@ -10,7 +10,14 @@ backend/app/models/__init__.py
|
|||||||
from app.models.agent import Agent, AgentDirectoryMember, AgentGuide, PermissionRequest
|
from app.models.agent import Agent, AgentDirectoryMember, AgentGuide, PermissionRequest
|
||||||
from app.models.base import Base, user_agent_permissions
|
from app.models.base import Base, user_agent_permissions
|
||||||
from app.models.permission_role import PermissionRole, permission_role_agents, user_permission_roles
|
from app.models.permission_role import PermissionRole, permission_role_agents, user_permission_roles
|
||||||
from app.models.chat import ChatLog, ChatSession, ChatToolRun, Feedback, GeneralFeedback
|
from app.models.chat import (
|
||||||
|
ChatLog,
|
||||||
|
ChatSession,
|
||||||
|
ChatToolRun,
|
||||||
|
Feedback,
|
||||||
|
GeneralFeedback,
|
||||||
|
GeneralFeedbackImage,
|
||||||
|
)
|
||||||
from app.models.content import Announcement, FaqHotCandidate, QuickQuestion, ZlLanguage
|
from app.models.content import Announcement, FaqHotCandidate, QuickQuestion, ZlLanguage
|
||||||
from app.models.department import Department
|
from app.models.department import Department
|
||||||
from app.models.linked_service import LinkedService
|
from app.models.linked_service import LinkedService
|
||||||
@@ -281,6 +288,7 @@ __all__ = [
|
|||||||
'ChatToolRun',
|
'ChatToolRun',
|
||||||
'Feedback',
|
'Feedback',
|
||||||
'GeneralFeedback',
|
'GeneralFeedback',
|
||||||
|
'GeneralFeedbackImage',
|
||||||
'PermissionRequest',
|
'PermissionRequest',
|
||||||
'QuickQuestion',
|
'QuickQuestion',
|
||||||
'FaqHotCandidate',
|
'FaqHotCandidate',
|
||||||
|
|||||||
@@ -135,3 +135,22 @@ class GeneralFeedback(Base):
|
|||||||
# 关闭时间:记录何时被处理/关闭,用于「本月已关闭」统计
|
# 关闭时间:记录何时被处理/关闭,用于「本月已关闭」统计
|
||||||
closed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
closed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||||
|
# 反馈附件截图列表:按 sort_order 排序;级联删除随反馈一并移除
|
||||||
|
images: Mapped[list['GeneralFeedbackImage']] = relationship(
|
||||||
|
order_by='GeneralFeedbackImage.sort_order', cascade='all, delete-orphan'
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class GeneralFeedbackImage(Base):
|
||||||
|
"""
|
||||||
|
通用意见反馈附件表
|
||||||
|
用途:关联 general_feedbacks 与 file_assets,一条反馈可带多张截图;asset_id 唯一,一图只挂一条反馈
|
||||||
|
"""
|
||||||
|
|
||||||
|
__tablename__ = 'general_feedback_images'
|
||||||
|
|
||||||
|
id: Mapped[int] = mapped_column(primary_key=True)
|
||||||
|
feedback_id: Mapped[int] = mapped_column(ForeignKey('general_feedbacks.id'), index=True)
|
||||||
|
asset_id: Mapped[int] = mapped_column(ForeignKey('file_assets.id'), unique=True)
|
||||||
|
sort_order: Mapped[int] = mapped_column(default=0)
|
||||||
|
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||||
@@ -16,8 +16,9 @@ from sqlalchemy import asc, desc, func, or_
|
|||||||
|
|
||||||
from app import db
|
from app import db
|
||||||
from app.core.errors import NotFoundError
|
from app.core.errors import NotFoundError
|
||||||
from app.models import Agent, ChatLog, Feedback, GeneralFeedback, User
|
from app.models import Agent, ChatLog, Feedback, FileAsset, GeneralFeedback, GeneralFeedbackImage, User
|
||||||
from app.models.base import user_agent_permissions
|
from app.models.base import user_agent_permissions
|
||||||
|
from app.services.file_assets.service import read_asset_bytes
|
||||||
|
|
||||||
USAGE_BY_USER_TOP_LIMIT = 50
|
USAGE_BY_USER_TOP_LIMIT = 50
|
||||||
APPLICATION_REPORT_PAGE_SIZE_MAX = 100
|
APPLICATION_REPORT_PAGE_SIZE_MAX = 100
|
||||||
@@ -36,6 +37,16 @@ USAGE_LOW_AGENT_MAX_CHATS = 2
|
|||||||
# 运营提醒:低使用应用最多返回条数
|
# 运营提醒:低使用应用最多返回条数
|
||||||
USAGE_LOW_AGENT_LIST_LIMIT = 5
|
USAGE_LOW_AGENT_LIST_LIMIT = 5
|
||||||
|
|
||||||
|
# 反馈图片响应 Content-Type 白名单:按资产扩展名固定响应类型。
|
||||||
|
# [SECURITY] 存储 mime_type 来自上传时客户端 multipart 头,不可信;代理内联输出时
|
||||||
|
# 若原样透传可被伪造为 text/html 等,构成存储型 XSS 面,故一律按扩展名收敛。
|
||||||
|
FEEDBACK_IMAGE_CONTENT_TYPES = {
|
||||||
|
'png': 'image/png',
|
||||||
|
'jpg': 'image/jpeg',
|
||||||
|
'jpeg': 'image/jpeg',
|
||||||
|
'webp': 'image/webp',
|
||||||
|
}
|
||||||
|
|
||||||
# 使用分析时间范围:key → 回溯天数(与前端下拉选项一致)
|
# 使用分析时间范围:key → 回溯天数(与前端下拉选项一致)
|
||||||
USAGE_RANGE_DAYS = {
|
USAGE_RANGE_DAYS = {
|
||||||
'7d': 7,
|
'7d': 7,
|
||||||
@@ -557,6 +568,39 @@ def _apply_general_feedback_filters(query, query_params: dict[str, str]):
|
|||||||
return query
|
return query
|
||||||
|
|
||||||
|
|
||||||
|
def _attach_general_feedback_images(rows: list[dict], feedback_ids: list[int]) -> None:
|
||||||
|
"""
|
||||||
|
批量回填每行 images 元数据(单查询,按 sort_order 排序),无图行置空列表。
|
||||||
|
|
||||||
|
用途:通用反馈报表行内附图元数据(前端缩略图入口);单条 IN 查询避免 N+1。
|
||||||
|
逻辑:GeneralFeedbackImage join FileAsset 按 feedback_id 批量取行,
|
||||||
|
按 (sort_order, id) 升序分组后写回各行的 'images' 键。
|
||||||
|
Args:
|
||||||
|
rows: list_general_feedbacks_report 构建出的行字典列表(含 'id' 键),原地修改。
|
||||||
|
feedback_ids: rows 对应的反馈 ID 列表。
|
||||||
|
"""
|
||||||
|
if not feedback_ids:
|
||||||
|
return
|
||||||
|
records = (
|
||||||
|
db.session.query(GeneralFeedbackImage, FileAsset)
|
||||||
|
.join(FileAsset, FileAsset.id == GeneralFeedbackImage.asset_id)
|
||||||
|
.filter(GeneralFeedbackImage.feedback_id.in_(feedback_ids))
|
||||||
|
.order_by(asc(GeneralFeedbackImage.sort_order), asc(GeneralFeedbackImage.id))
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
grouped: dict[int, list[dict]] = {}
|
||||||
|
for image, asset in records:
|
||||||
|
grouped.setdefault(int(image.feedback_id), []).append({
|
||||||
|
'image_id': int(image.id),
|
||||||
|
'asset_no': asset.asset_no,
|
||||||
|
'original_filename': asset.original_filename,
|
||||||
|
'file_size': int(asset.file_size or 0),
|
||||||
|
'sort_order': int(image.sort_order or 0),
|
||||||
|
})
|
||||||
|
for row in rows:
|
||||||
|
row['images'] = grouped.get(int(row['id']), [])
|
||||||
|
|
||||||
|
|
||||||
def list_general_feedbacks_report(query_params: dict[str, str]) -> list[dict]:
|
def list_general_feedbacks_report(query_params: dict[str, str]) -> list[dict]:
|
||||||
"""通用反馈列表(报表页)。"""
|
"""通用反馈列表(报表页)。"""
|
||||||
query = (
|
query = (
|
||||||
@@ -586,9 +630,48 @@ def list_general_feedbacks_report(query_params: dict[str, str]) -> list[dict]:
|
|||||||
row['real_name'] = real_name
|
row['real_name'] = real_name
|
||||||
row['department'] = department
|
row['department'] = department
|
||||||
rows.append(row)
|
rows.append(row)
|
||||||
|
_attach_general_feedback_images(rows, [row['id'] for row in rows])
|
||||||
return rows
|
return rows
|
||||||
|
|
||||||
|
|
||||||
|
def get_general_feedback_image_payload(feedback_id: int, image_id: int) -> dict:
|
||||||
|
"""
|
||||||
|
读取反馈图片字节(管理端代理输出,不走 MinIO 预签名,见 spec D6)。
|
||||||
|
|
||||||
|
用途:管理端报表页内联预览反馈截图;由 api/admin/reports.py 的 raw 路由调用。
|
||||||
|
逻辑:校验 image 归属该 feedback → 校验资产未删除 → read_asset_bytes 读字节
|
||||||
|
(内部再拦过期/已删除的 FILE_ASSET.*),错配一律按不存在处理避免探测他人资产。
|
||||||
|
响应 Content-Type 按扩展名白名单(FEEDBACK_IMAGE_CONTENT_TYPES)固定,
|
||||||
|
不透传存储 mime(其来自客户端上传头,不可信)。
|
||||||
|
Args:
|
||||||
|
feedback_id: 反馈 ID;image 必须归属该反馈,错配按不存在处理。
|
||||||
|
image_id: 反馈附件图片 ID。
|
||||||
|
Returns:
|
||||||
|
{'data': bytes, 'mime_type': str, 'filename': str};mime_type 由扩展名白名单决定,
|
||||||
|
未知扩展名(历史/边界行)降级 application/octet-stream。
|
||||||
|
Raises:
|
||||||
|
NotFoundError: code=FEEDBACK.IMAGE_NOT_FOUND——image 不存在、不属于该反馈或资产已删除。
|
||||||
|
"""
|
||||||
|
image = (
|
||||||
|
db.session.query(GeneralFeedbackImage)
|
||||||
|
.filter_by(id=image_id, feedback_id=feedback_id)
|
||||||
|
.first()
|
||||||
|
)
|
||||||
|
if image is None:
|
||||||
|
raise NotFoundError(code='FEEDBACK.IMAGE_NOT_FOUND', message='反馈图片不存在')
|
||||||
|
asset = db.session.get(FileAsset, image.asset_id)
|
||||||
|
if asset is None or asset.deleted_at is not None:
|
||||||
|
raise NotFoundError(code='FEEDBACK.IMAGE_NOT_FOUND', message='反馈图片不存在')
|
||||||
|
data = read_asset_bytes(asset)
|
||||||
|
# [SECURITY] 提交时仅校验扩展名白名单,存储 mime 仍是客户端自报值;响应类型只能信扩展名
|
||||||
|
mime_type = FEEDBACK_IMAGE_CONTENT_TYPES.get(str(asset.extension or '').lower(), 'application/octet-stream')
|
||||||
|
return {
|
||||||
|
'data': data,
|
||||||
|
'mime_type': mime_type,
|
||||||
|
'filename': asset.original_filename,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
def count_general_feedbacks_report(query_params: dict[str, str]) -> dict:
|
def count_general_feedbacks_report(query_params: dict[str, str]) -> dict:
|
||||||
"""通用反馈计数。"""
|
"""通用反馈计数。"""
|
||||||
query = db.session.query(GeneralFeedback).outerjoin(User, User.id == GeneralFeedback.user_id)
|
query = db.session.query(GeneralFeedback).outerjoin(User, User.id == GeneralFeedback.user_id)
|
||||||
|
|||||||
@@ -129,6 +129,10 @@ def build_feedback_markdown(feedback: GeneralFeedback, user: User | None) -> str
|
|||||||
lines.append(f'>来源页面:{feedback.source_page}')
|
lines.append(f'>来源页面:{feedback.source_page}')
|
||||||
if feedback.chat_log_id:
|
if feedback.chat_log_id:
|
||||||
lines.append(f'>关联对话:{feedback.chat_log_id}')
|
lines.append(f'>关联对话:{feedback.chat_log_id}')
|
||||||
|
# 附图行:仅在有截图时展示数量,置于「反馈内容」之前,便于处理人先感知附件再读正文
|
||||||
|
image_count = len(feedback.images or [])
|
||||||
|
if image_count:
|
||||||
|
lines.append(f'>附图:{image_count} 张')
|
||||||
lines.extend(['', '**反馈内容:**', content or '-'])
|
lines.extend(['', '**反馈内容:**', content or '-'])
|
||||||
if report_url:
|
if report_url:
|
||||||
lines.extend(['', f'[打开后台报表]({report_url})'])
|
lines.extend(['', f'[打开后台报表]({report_url})'])
|
||||||
|
|||||||
@@ -0,0 +1,24 @@
|
|||||||
|
"""合并意见反馈附图表与设备验收评审两条 Alembic 头
|
||||||
|
|
||||||
|
Revision ID: 7e5bc4bc0cbc
|
||||||
|
Revises: mh24f5a6b7c8, sxw4m73amjyh
|
||||||
|
Create Date: 2026-10-29 11:00:46.546116
|
||||||
|
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision = '7e5bc4bc0cbc'
|
||||||
|
down_revision = ('mh24f5a6b7c8', 'sxw4m73amjyh')
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade():
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade():
|
||||||
|
pass
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
"""合并用户多角色与意见反馈附图两条 Alembic 头
|
||||||
|
|
||||||
|
Revision ID: c375467a21f9
|
||||||
|
Revises: 7e5bc4bc0cbc, pr0a1b2c3d4e5
|
||||||
|
Create Date: 2026-10-29 12:41:08.055302
|
||||||
|
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision = 'c375467a21f9'
|
||||||
|
down_revision = ('7e5bc4bc0cbc', 'pr0a1b2c3d4e5')
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade():
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade():
|
||||||
|
pass
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
"""add general_feedback_images table
|
||||||
|
|
||||||
|
backend/migrations/versions/sxw4m73amjyh_add_general_feedback_images.py
|
||||||
|
用途:创建意见反馈截图附件关联表 general_feedback_images,一条反馈可挂多张截图(asset_id 唯一,一图只挂一条反馈)。
|
||||||
|
依赖:mh23e4f5a6b7(FAQ 模糊匹配与库存异动自然键两条迁移头的合并节点,当前唯一 head)。
|
||||||
|
逻辑:upgrade 仅建表(id/feedback_id/asset_id/sort_order/created_at + feedback_id 索引 + asset_id 唯一约束);
|
||||||
|
downgrade 按相反顺序删索引、删表;删除反馈时级联删除附件为 ORM 层行为(GeneralFeedback.images cascade)。
|
||||||
|
|
||||||
|
Revision ID: sxw4m73amjyh
|
||||||
|
Revises: mh23e4f5a6b7
|
||||||
|
Create Date: 2026-10-26 16:11:31.000000
|
||||||
|
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision = 'sxw4m73amjyh'
|
||||||
|
down_revision = 'mh23e4f5a6b7'
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
# ### commands auto generated by Alembic - please adjust! ###
|
||||||
|
op.create_table(
|
||||||
|
'general_feedback_images',
|
||||||
|
sa.Column('id', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('feedback_id', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('asset_id', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('sort_order', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('created_at', sa.DateTime(), nullable=False),
|
||||||
|
sa.ForeignKeyConstraint(['asset_id'], ['file_assets.id'], ),
|
||||||
|
sa.ForeignKeyConstraint(['feedback_id'], ['general_feedbacks.id'], ),
|
||||||
|
sa.PrimaryKeyConstraint('id'),
|
||||||
|
sa.UniqueConstraint('asset_id'),
|
||||||
|
)
|
||||||
|
op.create_index(
|
||||||
|
op.f('ix_general_feedback_images_feedback_id'),
|
||||||
|
'general_feedback_images',
|
||||||
|
['feedback_id'],
|
||||||
|
unique=False,
|
||||||
|
)
|
||||||
|
# ### end Alembic commands ###
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
# ### commands auto generated by Alembic - please adjust! ###
|
||||||
|
op.drop_index(
|
||||||
|
op.f('ix_general_feedback_images_feedback_id'),
|
||||||
|
table_name='general_feedback_images',
|
||||||
|
)
|
||||||
|
op.drop_table('general_feedback_images')
|
||||||
|
# ### end Alembic commands ###
|
||||||
@@ -0,0 +1,256 @@
|
|||||||
|
"""通用意见反馈提交 API 契约测试(POST /api/user/feedback 携带图片资产)。
|
||||||
|
|
||||||
|
用途:锁定反馈提交接口外部契约——image_asset_nos 按顺序落 general_feedback_images
|
||||||
|
并把 FileAsset 置为 referenced(reference_count+1、expires_at 清空),
|
||||||
|
他人资产/非图片/已被引用/超 5 张等非法输入整单拒绝且不落任何行
|
||||||
|
(FILE_ASSET.* 与 FEEDBACK.IMAGE_* 错误码),纯文本提交保持旧契约。
|
||||||
|
依赖:app/client 夹具(create_app('testing') + create_all)、issue_local_access_token、
|
||||||
|
parse_api_error(错误 envelope 断言);前置数据直接落 User/FileAsset 行。
|
||||||
|
逻辑:校验逻辑由 handlers.submit_general_feedback 承载,本文件只测 API 壳
|
||||||
|
(鉴权/状态码/错误码/落库副作用/回归路径)。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from uuid import uuid4
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from app import db
|
||||||
|
from app.core.auth.jwt import issue_local_access_token
|
||||||
|
from app.models import FileAsset, GeneralFeedback, GeneralFeedbackImage, User
|
||||||
|
from tests.conftest import parse_api_error
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(autouse=True)
|
||||||
|
def _disable_wecom_feedback_notify(app):
|
||||||
|
"""测试绝不触发真实企微群通知(2026-10-26 曾因未隔离 webhook 向真实群发出消息)。"""
|
||||||
|
app.config["WECOM_FEEDBACK_NOTIFY_ENABLED"] = False
|
||||||
|
|
||||||
|
|
||||||
|
def _headers(user: User) -> dict:
|
||||||
|
"""为指定用户签发 Bearer JWT 请求头(须在 app context 内调用)。"""
|
||||||
|
token = issue_local_access_token(user)
|
||||||
|
return {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
|
||||||
|
|
||||||
|
|
||||||
|
def _create_user(username: str, role: str = "user") -> User:
|
||||||
|
"""按用户名幂等落一个测试用户。"""
|
||||||
|
user = db.session.query(User).filter_by(username=username).first()
|
||||||
|
if not user:
|
||||||
|
user = User(username=username, email=f"{username}@example.com", role=role, status="active")
|
||||||
|
user.set_password("x")
|
||||||
|
db.session.add(user)
|
||||||
|
db.session.commit()
|
||||||
|
return user
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def user_headers(app):
|
||||||
|
"""普通用户 JWT 请求头。"""
|
||||||
|
with app.app_context():
|
||||||
|
return _headers(_create_user("fbuser"))
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def admin_headers(app):
|
||||||
|
"""平台管理员 JWT 请求头。"""
|
||||||
|
with app.app_context():
|
||||||
|
return _headers(_create_user("fbadmin", role="admin"))
|
||||||
|
|
||||||
|
|
||||||
|
def _make_asset(user_id: int, ext: str = "png", mime: str = "image/png", *, reference_count: int = 0, lifecycle: str = "temporary") -> FileAsset:
|
||||||
|
"""直接落一条 ready/temporary 的 FileAsset 行(不经过 MinIO)。"""
|
||||||
|
asset = FileAsset(
|
||||||
|
asset_no=f"FA-TEST-{uuid4().hex[:8].upper()}", owner_user_id=int(user_id),
|
||||||
|
original_filename=f"screenshot.{ext}", storage_provider="minio", storage_bucket="test",
|
||||||
|
storage_key=f"test/{user_id}/{uuid4().hex}", content_hash="0" * 64, file_size=1024,
|
||||||
|
mime_type=mime, extension=ext, upload_status="ready",
|
||||||
|
lifecycle_status=lifecycle, reference_count=reference_count,
|
||||||
|
)
|
||||||
|
db.session.add(asset)
|
||||||
|
db.session.commit()
|
||||||
|
return asset
|
||||||
|
|
||||||
|
|
||||||
|
def _submit_payload(**overrides) -> dict:
|
||||||
|
"""合法反馈提交载荷基线(纯文本,不带图片)。"""
|
||||||
|
payload = {
|
||||||
|
"feedback_type": "问题反馈", "feedback_module": "知识库", "content": "测试反馈内容",
|
||||||
|
"source_page": "workspace",
|
||||||
|
}
|
||||||
|
payload.update(overrides)
|
||||||
|
return payload
|
||||||
|
|
||||||
|
|
||||||
|
def test_submit_with_images_claims_assets(app, client, user_headers):
|
||||||
|
"""带图提交:两图按顺序落库,资产被引用(reference_count=1、referenced、expires_at 清空)。"""
|
||||||
|
with app.app_context():
|
||||||
|
u = db.session.query(User).filter_by(username="fbuser").first()
|
||||||
|
a1 = _make_asset(u.id)
|
||||||
|
a2 = _make_asset(u.id, ext="jpg", mime="image/jpeg")
|
||||||
|
# asset_no 须在 app context 内取出:context 弹出后 ORM 实例已脱管,属性不可再读
|
||||||
|
asset_nos = [a1.asset_no, a2.asset_no]
|
||||||
|
resp = client.post("/api/user/feedback", headers=user_headers, json={
|
||||||
|
"feedback_type": "问题反馈", "feedback_module": "知识库", "content": "带上截图",
|
||||||
|
"source_page": "workspace", "image_asset_nos": asset_nos,
|
||||||
|
})
|
||||||
|
assert resp.status_code == 200
|
||||||
|
with app.app_context():
|
||||||
|
imgs = GeneralFeedbackImage.query.order_by(GeneralFeedbackImage.sort_order).all()
|
||||||
|
assert [i.sort_order for i in imgs] == [0, 1]
|
||||||
|
for i in imgs:
|
||||||
|
asset = db.session.get(FileAsset, i.asset_id)
|
||||||
|
assert asset.reference_count == 1
|
||||||
|
assert asset.lifecycle_status == "referenced"
|
||||||
|
assert asset.expires_at is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_submit_rejects_foreign_asset(app, client, user_headers):
|
||||||
|
"""他人资产 → 403 FILE_ASSET.FORBIDDEN,反馈不落库。"""
|
||||||
|
with app.app_context():
|
||||||
|
other = _create_user("fbother")
|
||||||
|
foreign = _make_asset(other.id)
|
||||||
|
# asset_no 须在 app context 内取出:context 弹出后 ORM 实例已脱管,属性不可再读
|
||||||
|
foreign_no = foreign.asset_no
|
||||||
|
resp = client.post("/api/user/feedback", headers=user_headers, json=_submit_payload(
|
||||||
|
content="挂别人资产", image_asset_nos=[foreign_no],
|
||||||
|
))
|
||||||
|
assert resp.status_code == 403
|
||||||
|
assert parse_api_error(resp.get_json())["code"] == "FILE_ASSET.FORBIDDEN"
|
||||||
|
with app.app_context():
|
||||||
|
# 拒绝路径不落任何行:反馈与图片关联均为零
|
||||||
|
assert GeneralFeedbackImage.query.count() == 0
|
||||||
|
assert GeneralFeedback.query.count() == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_submit_rejects_non_image(app, client, user_headers):
|
||||||
|
"""ext='pdf' 的资产 → 400 FEEDBACK.IMAGE_INVALID。"""
|
||||||
|
with app.app_context():
|
||||||
|
u = db.session.query(User).filter_by(username="fbuser").first()
|
||||||
|
pdf_asset = _make_asset(u.id, ext="pdf", mime="application/pdf")
|
||||||
|
# asset_no 须在 app context 内取出:context 弹出后 ORM 实例已脱管,属性不可再读
|
||||||
|
pdf_no = pdf_asset.asset_no
|
||||||
|
resp = client.post("/api/user/feedback", headers=user_headers, json=_submit_payload(
|
||||||
|
content="挂非图片", image_asset_nos=[pdf_no],
|
||||||
|
))
|
||||||
|
assert resp.status_code == 400
|
||||||
|
assert parse_api_error(resp.get_json())["code"] == "FEEDBACK.IMAGE_INVALID"
|
||||||
|
with app.app_context():
|
||||||
|
# 拒绝路径不落任何行
|
||||||
|
assert GeneralFeedbackImage.query.count() == 0
|
||||||
|
assert GeneralFeedback.query.count() == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_submit_rejects_referenced_asset(app, client, user_headers):
|
||||||
|
"""reference_count=1 的图片资产 → 400 FEEDBACK.IMAGE_INVALID(防挂已被业务引用资产)。"""
|
||||||
|
with app.app_context():
|
||||||
|
u = db.session.query(User).filter_by(username="fbuser").first()
|
||||||
|
used = _make_asset(u.id, reference_count=1)
|
||||||
|
# asset_no 须在 app context 内取出:context 弹出后 ORM 实例已脱管,属性不可再读
|
||||||
|
used_no = used.asset_no
|
||||||
|
resp = client.post("/api/user/feedback", headers=user_headers, json=_submit_payload(
|
||||||
|
content="挂已引用资产", image_asset_nos=[used_no],
|
||||||
|
))
|
||||||
|
assert resp.status_code == 400
|
||||||
|
assert parse_api_error(resp.get_json())["code"] == "FEEDBACK.IMAGE_INVALID"
|
||||||
|
with app.app_context():
|
||||||
|
# 拒绝路径不落任何行
|
||||||
|
assert GeneralFeedbackImage.query.count() == 0
|
||||||
|
assert GeneralFeedback.query.count() == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_submit_rejects_too_many(app, client, user_headers):
|
||||||
|
"""6 个 asset_no → 400 FEEDBACK.IMAGE_TOO_MANY,反馈不落库。"""
|
||||||
|
asset_nos = [f"FA-TEST-{i:04d}" for i in range(6)]
|
||||||
|
resp = client.post("/api/user/feedback", headers=user_headers, json=_submit_payload(
|
||||||
|
content="一次挂六张", image_asset_nos=asset_nos,
|
||||||
|
))
|
||||||
|
assert resp.status_code == 400
|
||||||
|
assert parse_api_error(resp.get_json())["code"] == "FEEDBACK.IMAGE_TOO_MANY"
|
||||||
|
with app.app_context():
|
||||||
|
# 拒绝路径不落任何行
|
||||||
|
assert GeneralFeedbackImage.query.count() == 0
|
||||||
|
assert GeneralFeedback.query.count() == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_submit_text_only_keeps_legacy(app, client, user_headers):
|
||||||
|
"""不带 image_asset_nos:200,general_feedback_images 零行(回归)。"""
|
||||||
|
resp = client.post("/api/user/feedback", headers=user_headers, json=_submit_payload())
|
||||||
|
assert resp.status_code == 200
|
||||||
|
body = resp.get_json()
|
||||||
|
assert body.get("status") == "ok"
|
||||||
|
assert isinstance(body.get("id"), int)
|
||||||
|
with app.app_context():
|
||||||
|
assert GeneralFeedbackImage.query.count() == 0
|
||||||
|
assert GeneralFeedback.query.count() == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_report_rows_include_images(app, client, user_headers, admin_headers):
|
||||||
|
"""报表行含 images 元数据;无图行 images==[]。"""
|
||||||
|
with app.app_context():
|
||||||
|
u = db.session.query(User).filter_by(username="fbuser").first()
|
||||||
|
a1 = _make_asset(u.id)
|
||||||
|
# asset_no 须在 app context 内取出:context 弹出后 ORM 实例已脱管,属性不可再读
|
||||||
|
asset_no = a1.asset_no
|
||||||
|
resp = client.post("/api/user/feedback", headers=user_headers, json=_submit_payload(
|
||||||
|
content="带图反馈", image_asset_nos=[asset_no],
|
||||||
|
))
|
||||||
|
assert resp.status_code == 200
|
||||||
|
with_image_id = resp.get_json()["id"]
|
||||||
|
resp = client.post("/api/user/feedback", headers=user_headers, json=_submit_payload(content="纯文本反馈"))
|
||||||
|
assert resp.status_code == 200
|
||||||
|
text_only_id = resp.get_json()["id"]
|
||||||
|
|
||||||
|
resp = client.get("/api/admin/reports/general-feedbacks", headers=admin_headers)
|
||||||
|
assert resp.status_code == 200
|
||||||
|
rows = resp.get_json()
|
||||||
|
rows_by_id = {row["id"]: row for row in rows}
|
||||||
|
# 有图行:images[0] 键集合恰为 5 个元数据键,asset_no 与提交资产一致
|
||||||
|
with_image_row = rows_by_id[with_image_id]
|
||||||
|
assert len(with_image_row["images"]) == 1
|
||||||
|
assert set(with_image_row["images"][0].keys()) == {
|
||||||
|
"image_id", "asset_no", "original_filename", "file_size", "sort_order",
|
||||||
|
}
|
||||||
|
assert with_image_row["images"][0]["asset_no"] == asset_no
|
||||||
|
# 无图行:images 置空列表而非缺键
|
||||||
|
assert rows_by_id[text_only_id]["images"] == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_admin_image_raw_streams(app, client, user_headers, admin_headers, monkeypatch):
|
||||||
|
"""管理员经 raw 接口取到图片字节(Content-Type 按扩展名固定 + nosniff);错配 feedback_id → 404 FEEDBACK.IMAGE_NOT_FOUND;非管理员 → 403。"""
|
||||||
|
# 隔离 MinIO:读取字节走本地假实现,提交仍只落库不触对象存储
|
||||||
|
monkeypatch.setattr(
|
||||||
|
"app.services.file_assets.service.file_asset_storage.get_bytes",
|
||||||
|
lambda key: b"\x89PNG\r\n\x1a\nfake",
|
||||||
|
)
|
||||||
|
with app.app_context():
|
||||||
|
u = db.session.query(User).filter_by(username="fbuser").first()
|
||||||
|
a1 = _make_asset(u.id)
|
||||||
|
asset_no = a1.asset_no
|
||||||
|
resp = client.post("/api/user/feedback", headers=user_headers, json=_submit_payload(
|
||||||
|
content="取图反馈", image_asset_nos=[asset_no],
|
||||||
|
))
|
||||||
|
assert resp.status_code == 200
|
||||||
|
fb_id = resp.get_json()["id"]
|
||||||
|
with app.app_context():
|
||||||
|
img = GeneralFeedbackImage.query.filter_by(feedback_id=fb_id).first()
|
||||||
|
image_id = img.id
|
||||||
|
|
||||||
|
resp = client.get(f"/api/admin/reports/general-feedbacks/{fb_id}/images/{image_id}/raw", headers=admin_headers)
|
||||||
|
assert resp.status_code == 200
|
||||||
|
assert resp.data == b"\x89PNG\r\n\x1a\nfake"
|
||||||
|
assert resp.content_type.startswith("image/png")
|
||||||
|
# 安全响应头:Content-Type 按扩展名白名单固定后,仍禁用浏览器 MIME 嗅探(防伪造内容内联渲染)
|
||||||
|
assert resp.headers.get("X-Content-Type-Options") == "nosniff"
|
||||||
|
|
||||||
|
# 错配 feedback_id:image 不属于该反馈 → FEEDBACK.IMAGE_NOT_FOUND(而非 FILE_ASSET.*)
|
||||||
|
resp = client.get(
|
||||||
|
f"/api/admin/reports/general-feedbacks/{fb_id + 99999}/images/{image_id}/raw", headers=admin_headers,
|
||||||
|
)
|
||||||
|
assert resp.status_code == 404
|
||||||
|
assert parse_api_error(resp.get_json())["code"] == "FEEDBACK.IMAGE_NOT_FOUND"
|
||||||
|
|
||||||
|
# 非管理员访问 raw 接口 → 403
|
||||||
|
resp = client.get(f"/api/admin/reports/general-feedbacks/{fb_id}/images/{image_id}/raw", headers=user_headers)
|
||||||
|
assert resp.status_code == 403
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
"""
|
||||||
|
backend/tests/services/test_feedback_notify.py
|
||||||
|
|
||||||
|
用途:锁定企微反馈通知 markdown 组装契约——有图反馈在「反馈内容」段之前
|
||||||
|
多一行「附图:N 张」(N>0 时),无图反馈不得出现「附图」字样,
|
||||||
|
且其余既有行内容与顺序零改动。
|
||||||
|
依赖:app 夹具(create_app('testing') + db.create_all,不走迁移)、
|
||||||
|
GeneralFeedback/GeneralFeedbackImage/User/FileAsset 模型、
|
||||||
|
app.services.feedback_notify.build_feedback_markdown。
|
||||||
|
逻辑:build_feedback_markdown 为纯组装函数(不发网络请求),测试直接落
|
||||||
|
User/FileAsset/GeneralFeedback/GeneralFeedbackImage 行后调用并断言文本,
|
||||||
|
覆盖有图(2 张)与无图两条路径。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from uuid import uuid4
|
||||||
|
|
||||||
|
from app import db
|
||||||
|
from app.models import FileAsset, GeneralFeedback, GeneralFeedbackImage, User
|
||||||
|
from app.services.feedback_notify import build_feedback_markdown
|
||||||
|
|
||||||
|
|
||||||
|
def _create_user(username: str) -> User:
|
||||||
|
"""按用户名幂等落一个测试用户(GeneralFeedback.user_id 外键依赖)。"""
|
||||||
|
user = db.session.query(User).filter_by(username=username).first()
|
||||||
|
if not user:
|
||||||
|
user = User(username=username, email=f"{username}@example.com", role="user", status="active")
|
||||||
|
user.set_password("x")
|
||||||
|
db.session.add(user)
|
||||||
|
db.session.commit()
|
||||||
|
return user
|
||||||
|
|
||||||
|
|
||||||
|
def _make_asset(user_id: int) -> FileAsset:
|
||||||
|
"""直接落一条 ready/temporary 的图片 FileAsset 行(GeneralFeedbackImage.asset_id 外键依赖)。"""
|
||||||
|
asset = FileAsset(
|
||||||
|
asset_no=f"FA-TEST-{uuid4().hex[:8].upper()}", owner_user_id=int(user_id),
|
||||||
|
original_filename="screenshot.png", storage_provider="minio", storage_bucket="test",
|
||||||
|
storage_key=f"test/{user_id}/{uuid4().hex}", content_hash="0" * 64, file_size=1024,
|
||||||
|
mime_type="image/png", extension="png", upload_status="ready",
|
||||||
|
lifecycle_status="temporary", reference_count=0,
|
||||||
|
)
|
||||||
|
db.session.add(asset)
|
||||||
|
db.session.commit()
|
||||||
|
return asset
|
||||||
|
|
||||||
|
|
||||||
|
def _create_feedback(user: User, content: str) -> GeneralFeedback:
|
||||||
|
"""落一条最小可用的 GeneralFeedback 行(必填字段齐全)。"""
|
||||||
|
feedback = GeneralFeedback(
|
||||||
|
user_id=user.id, username=user.username,
|
||||||
|
feedback_type="问题反馈", feedback_module="知识库", content=content,
|
||||||
|
source_page="workspace",
|
||||||
|
)
|
||||||
|
db.session.add(feedback)
|
||||||
|
db.session.commit()
|
||||||
|
return feedback
|
||||||
|
|
||||||
|
|
||||||
|
def test_markdown_includes_image_count(app):
|
||||||
|
"""有图反馈:markdown 含「附图:2 张」行;无图反馈:不含「附图」。"""
|
||||||
|
with app.app_context():
|
||||||
|
user = _create_user("notifyuser")
|
||||||
|
# 有图反馈:2 条图片关联(asset_id 唯一,各自独立 FileAsset),走真实 images relationship
|
||||||
|
fb_with_images = _create_feedback(user, "这条反馈带两张截图")
|
||||||
|
db.session.add_all([
|
||||||
|
GeneralFeedbackImage(feedback_id=fb_with_images.id, asset_id=_make_asset(user.id).id, sort_order=0),
|
||||||
|
GeneralFeedbackImage(feedback_id=fb_with_images.id, asset_id=_make_asset(user.id).id, sort_order=1),
|
||||||
|
])
|
||||||
|
db.session.commit()
|
||||||
|
# 无图反馈:不落任何 GeneralFeedbackImage
|
||||||
|
fb_without_images = _create_feedback(user, "这条反馈没有截图")
|
||||||
|
|
||||||
|
md_with_images = build_feedback_markdown(fb_with_images, None)
|
||||||
|
md_without_images = build_feedback_markdown(fb_without_images, None)
|
||||||
|
|
||||||
|
# 有图:附图行存在,且必须位于「反馈内容」块之前
|
||||||
|
assert "附图:2 张" in md_with_images
|
||||||
|
assert md_with_images.index("附图:2 张") < md_with_images.index("**反馈内容:**")
|
||||||
|
# 无图:不得出现「附图」字样
|
||||||
|
assert "附图" not in md_without_images
|
||||||
@@ -103,6 +103,7 @@
|
|||||||
| ------------------ | ------ | ------------------------------------------------------------------------------------------------------------- |
|
| ------------------ | ------ | ------------------------------------------------------------------------------------------------------------- |
|
||||||
| 意见反馈入库 | 已实现 | 用户在 Workspace/Chat 提交意见后写入 `general_feedbacks`,后台报表可查看 |
|
| 意见反馈入库 | 已实现 | 用户在 Workspace/Chat 提交意见后写入 `general_feedbacks`,后台报表可查看 |
|
||||||
| 反馈企业微信群通知 | 已实现 | 反馈入库后通过 `WECOM_FEEDBACK_BOT_WEBHOOK` 即时推送到企业微信群;未配置 webhook 时静默跳过,不影响用户提交 |
|
| 反馈企业微信群通知 | 已实现 | 反馈入库后通过 `WECOM_FEEDBACK_BOT_WEBHOOK` 即时推送到企业微信群;未配置 webhook 时静默跳过,不影响用户提交 |
|
||||||
|
| 反馈截图附件 | 已实现 | 意见反馈支持粘贴/上传截图附件(每条最多 5 张),管理端报表可查看附图缩略图与大图预览 |
|
||||||
|
|
||||||
## 年度教育训练计划
|
## 年度教育训练计划
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,597 @@
|
|||||||
|
# 意见反馈截图附件 Implementation Plan
|
||||||
|
|
||||||
|
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||||
|
|
||||||
|
**Goal:** 意见反馈弹窗支持粘贴/选图上传截图(整页换 Element Plus),图片随反馈入库,管理端报表可看缩略图与大图,企微通知加「附图:N 张」文字行。
|
||||||
|
|
||||||
|
**Architecture:** 复用平台文件资产设施(`POST /api/files/assets` → MinIO + 72h 孤儿清理)。用户选图后立即上传,提交时 JSON 携带 `image_asset_nos[]`,后端建子表 `general_feedback_images` 关联并调 `mark_asset_referenced` 防清理。管理端图片由后端 raw 接口代理输出(不走 MinIO 预签名 URL,原因见 spec D6),前端 `requestBlob` 取 blob 展示。
|
||||||
|
|
||||||
|
**Tech Stack:** Flask + SQLAlchemy 2.0 + Alembic;Vue 3 + TS + Element Plus 2.14.7;MinIO。
|
||||||
|
|
||||||
|
**Spec:** `docs/superpowers/specs/2026-10-26-feedback-image-attachment-design.md`(执行者必须同时阅读,数值与决策以 spec 为准)
|
||||||
|
|
||||||
|
## Global Constraints
|
||||||
|
|
||||||
|
- 每条反馈最多 **5** 张图,单张 **10MB**,格式仅 png/jpg/jpeg/webp;客户端与服务端双重校验(spec D4)。
|
||||||
|
- 仅允许挂载 `reference_count == 0` 且 `lifecycle_status == 'temporary'` 的资产(spec D9)。
|
||||||
|
- `POST /api/user/feedback` 响应契约不变:`{'status':'ok','id':<int>}`(spec D8)。
|
||||||
|
- 新增错误码 `FEEDBACK.IMAGE_INVALID` / `FEEDBACK.IMAGE_TOO_MANY` / `FEEDBACK.IMAGE_NOT_FOUND` 必须同步四语言 `frontend/src/locales/{zh-CN,zh-TW,en,th}/errors.json`(键名为下划线风格,如 `FEEDBACK_IMAGE_INVALID`)。
|
||||||
|
- 所有新增文案四语言齐备,禁止硬编码中文。
|
||||||
|
- 反馈弹窗整页 Element Plus,禁止再出现 `btn-*`/`input-field`/`select-field`/手写 `<button>`/`<select>`/`<textarea>`(管理端 ReportsPage 例外:只加展示型 `<img>` 与 overlay,不新增表单控件)。
|
||||||
|
- 不新增任何第三方依赖。
|
||||||
|
- 新文件顶部按 AGENTS.md §5 写文件层块注释;新增/调整的核心函数带 docstring/JSDoc。
|
||||||
|
- 提交信息符合 Conventional Commits:`type(scope): 中文祈使句`(scope 英文 kebab)。
|
||||||
|
|
||||||
|
## Review Focus
|
||||||
|
|
||||||
|
spec 隐含但任务测试未覆盖、最容易咬人的五类输入(人工验证时重点看):
|
||||||
|
|
||||||
|
1. **粘贴内容同时含文本与图片**(聊天工具复制):只有图片项成为附件,文本粘贴进输入框的行为不得被破坏 → Task 5 的 `onPaste` 只在有 image item 时 `preventDefault`;人工验证。
|
||||||
|
2. **同一张图被并发/重复提交到两条反馈**:应被拒(`FEEDBACK.IMAGE_INVALID`),不能 500 → Task 2 的 commit 包 `IntegrityError` 兜底;测试 `test_submit_rejects_referenced_asset` 钉串行路径。
|
||||||
|
3. **报表页满屏 5 图大图**(慢网络):无图行零图片请求,缩略图 `loading="lazy"` → Task 6 人工验证 Network 面板。
|
||||||
|
4. **历史无图反馈**:images 列显示 `-`,排序/筛选/导出不受影响 → Task 4 测试 `test_report_rows_include_images` 含无图行断言。
|
||||||
|
5. **一次粘贴超过 5 张**:整批拒绝并提示 `feedback.upload.maxCount`,不得静默截取前 5 张 → Task 5 `addImages` 的行为钉死;人工验证。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Task 1: 数据模型与迁移
|
||||||
|
|
||||||
|
**Files:**
|
||||||
|
- Modify: `backend/app/models/chat.py`(在 `GeneralFeedback` 类之后追加)
|
||||||
|
- Modify: `backend/app/models/__init__.py:13`(import 行)与 `__all__` 中 `'GeneralFeedback'` 旁
|
||||||
|
- Create: `backend/migrations/versions/<rev>_add_general_feedback_images.py`(由 flask db migrate 生成)
|
||||||
|
|
||||||
|
**Interfaces:**
|
||||||
|
- Produces: 模型 `GeneralFeedbackImage`(表 `general_feedback_images`),字段:`id`(PK)、`feedback_id`(FK `general_feedbacks.id`,NOT NULL,index)、`asset_id`(FK `file_assets.id`,NOT NULL,**unique**)、`sort_order`(Integer,NOT NULL,default 0)、`created_at`(DateTime,default `datetime.utcnow`)。`GeneralFeedback` 上新增 `images: Mapped[list['GeneralFeedbackImage']] = relationship(order_by='GeneralFeedbackImage.sort_order', cascade='all, delete-orphan')`。后续所有任务经 `from app.models import GeneralFeedbackImage` 引用。
|
||||||
|
|
||||||
|
- [ ] **Step 1: 在 `backend/app/models/chat.py` 追加模型**
|
||||||
|
|
||||||
|
```python
|
||||||
|
class GeneralFeedbackImage(Base):
|
||||||
|
"""
|
||||||
|
通用意见反馈附件图表
|
||||||
|
用途:关联 general_feedbacks 与 file_assets,一条反馈可带多张截图;asset_id 唯一,一图只挂一条反馈
|
||||||
|
"""
|
||||||
|
|
||||||
|
__tablename__ = 'general_feedback_images'
|
||||||
|
|
||||||
|
id: Mapped[int] = mapped_column(primary_key=True)
|
||||||
|
feedback_id: Mapped[int] = mapped_column(ForeignKey('general_feedbacks.id'), index=True)
|
||||||
|
asset_id: Mapped[int] = mapped_column(ForeignKey('file_assets.id'), unique=True)
|
||||||
|
sort_order: Mapped[int] = mapped_column(default=0)
|
||||||
|
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||||
|
```
|
||||||
|
|
||||||
|
并在 `GeneralFeedback` 类体内加 `images` relationship(如上 Interfaces 所示,含注释说明级联随反馈删除)。
|
||||||
|
|
||||||
|
- [ ] **Step 2: 在 `backend/app/models/__init__.py` 注册导出**
|
||||||
|
|
||||||
|
第 13 行 import 加入 `GeneralFeedbackImage`;`__all__` 列表在 `'GeneralFeedback'` 后加 `'GeneralFeedbackImage'`。
|
||||||
|
|
||||||
|
- [ ] **Step 3: 生成迁移**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd backend && source venv/bin/activate # Windows Git Bash: source venv/Scripts/activate
|
||||||
|
flask db migrate -m "add general_feedback_images table"
|
||||||
|
```
|
||||||
|
|
||||||
|
检查生成的文件:`down_revision` 必须为 `'mh23e4f5a6b7'`(当前单 head),upgrade 只含 `create_table('general_feedback_images', ...)`(id/feedback_id/asset_id/sort_order/created_at + 索引 + unique 约束),无其他意外变更。若本地无可用数据库连接,则手写迁移文件(仿 `backend/migrations/versions/dq2e3f4g5h6i_add_per_source_inventory_rpa_attempts.py` 的结构,`revision` 用新随机 12 位 id)。
|
||||||
|
|
||||||
|
- [ ] **Step 4: 验证迁移链与模型可导入**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
flask db heads # 期望:仅一个 head,即新 revision
|
||||||
|
python -c "from app.models import GeneralFeedbackImage; print(GeneralFeedbackImage.__tablename__)"
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected: 单 head;打印 `general_feedback_images`。
|
||||||
|
|
||||||
|
- [ ] **Step 5: Commit**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git add backend/app/models/chat.py backend/app/models/__init__.py backend/migrations/versions/
|
||||||
|
git commit -m "feat(feedback): 新增反馈图片关联表与模型"
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Task 2: 提交接口携带图片资产(后端)
|
||||||
|
|
||||||
|
**Files:**
|
||||||
|
- Modify: `backend/app/api/user/handlers.py:122-176`(`submit_general_feedback`)
|
||||||
|
- Test: `backend/tests/api/test_general_feedback_api.py`(新建)
|
||||||
|
|
||||||
|
**Interfaces:**
|
||||||
|
- Consumes: Task 1 的 `GeneralFeedbackImage`;现有 `get_asset_for_user(asset_no: str, user_id: int) -> FileAsset`(`app/services/file_assets/service.py:119`,NotFoundError/ForbiddenError)、`mark_asset_referenced(asset: FileAsset) -> None`(`service.py:430`)。
|
||||||
|
- Produces: `POST /api/user/feedback` 请求体新增可选 `image_asset_nos: string[]`(顺序即 sort_order)。校验失败抛 `ValidationError(code='FEEDBACK.IMAGE_TOO_MANY'|'FEEDBACK.IMAGE_INVALID', message=...)` / 沿用 `get_asset_for_user` 的 `FILE_ASSET.*` 异常。
|
||||||
|
|
||||||
|
- [ ] **Step 1: 写失败测试**
|
||||||
|
|
||||||
|
新建 `backend/tests/api/test_general_feedback_api.py`。文件头块注释说明用途/依赖/逻辑(AGENTS.md §5.1)。复用全局 `app`/`client` 夹具(`backend/tests/conftest.py:562,692`,`create_app('testing')` + `create_all`)。鉴权仿 `backend/tests/api/test_transfer_type_api.py:60-77`:
|
||||||
|
|
||||||
|
```python
|
||||||
|
from app.core.auth.jwt import issue_local_access_token
|
||||||
|
|
||||||
|
def _headers(user: User) -> dict:
|
||||||
|
"""为指定用户签发 Bearer JWT 请求头(须在 app context 内调用)。"""
|
||||||
|
token = issue_local_access_token(user)
|
||||||
|
return {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def user_headers(app):
|
||||||
|
"""普通用户 JWT 请求头。"""
|
||||||
|
with app.app_context():
|
||||||
|
user = db.session.query(User).filter_by(username="fbuser").first()
|
||||||
|
if not user:
|
||||||
|
user = User(username="fbuser", email="fbuser@example.com", role="user", status="active")
|
||||||
|
user.set_password("x")
|
||||||
|
db.session.add(user)
|
||||||
|
db.session.commit()
|
||||||
|
return _headers(user)
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def admin_headers(app):
|
||||||
|
"""平台管理员 JWT 请求头。"""
|
||||||
|
with app.app_context():
|
||||||
|
user = db.session.query(User).filter_by(username="fbadmin").first()
|
||||||
|
if not user:
|
||||||
|
user = User(username="fbadmin", email="fbadmin@example.com", role="admin", status="active")
|
||||||
|
user.set_password("x")
|
||||||
|
db.session.add(user)
|
||||||
|
db.session.commit()
|
||||||
|
return _headers(user)
|
||||||
|
|
||||||
|
def _make_asset(user_id: int, ext: str = "png", mime: str = "image/png", *, reference_count: int = 0, lifecycle: str = "temporary") -> FileAsset:
|
||||||
|
"""直接落一条 ready/temporary 的 FileAsset 行(不经过 MinIO)。"""
|
||||||
|
asset = FileAsset(
|
||||||
|
asset_no=f"FA-TEST-{uuid4().hex[:8].upper()}", owner_user_id=int(user_id),
|
||||||
|
original_filename=f"screenshot.{ext}", storage_provider="minio", storage_bucket="test",
|
||||||
|
storage_key=f"test/{user_id}/{uuid4().hex}", content_hash="0" * 64, file_size=1024,
|
||||||
|
mime_type=mime, extension=ext, upload_status="ready",
|
||||||
|
lifecycle_status=lifecycle, reference_count=reference_count,
|
||||||
|
)
|
||||||
|
db.session.add(asset)
|
||||||
|
db.session.commit()
|
||||||
|
return asset
|
||||||
|
```
|
||||||
|
|
||||||
|
测试用例(本任务实现前 6 个;断言错误码用 `tests/conftest.py` 的 `parse_api_error`):
|
||||||
|
|
||||||
|
```python
|
||||||
|
def test_submit_with_images_claims_assets(app, client, user_headers):
|
||||||
|
"""带图提交:两图按顺序落库,资产被引用(reference_count=1、referenced、expires_at 清空)。"""
|
||||||
|
with app.app_context():
|
||||||
|
u = db.session.query(User).filter_by(username="fbuser").first()
|
||||||
|
a1 = _make_asset(u.id)
|
||||||
|
a2 = _make_asset(u.id, ext="jpg", mime="image/jpeg")
|
||||||
|
resp = client.post("/api/user/feedback", headers=user_headers, json={
|
||||||
|
"feedback_type": "问题反馈", "feedback_module": "知识库", "content": "带上截图",
|
||||||
|
"source_page": "workspace", "image_asset_nos": [a1.asset_no, a2.asset_no],
|
||||||
|
})
|
||||||
|
assert resp.status_code == 200
|
||||||
|
with app.app_context():
|
||||||
|
imgs = GeneralFeedbackImage.query.order_by(GeneralFeedbackImage.sort_order).all()
|
||||||
|
assert [i.sort_order for i in imgs] == [0, 1]
|
||||||
|
for i in imgs:
|
||||||
|
asset = db.session.get(FileAsset, i.asset_id)
|
||||||
|
assert asset.reference_count == 1
|
||||||
|
assert asset.lifecycle_status == "referenced"
|
||||||
|
assert asset.expires_at is None
|
||||||
|
|
||||||
|
def test_submit_rejects_foreign_asset(app, client, user_headers):
|
||||||
|
"""他人资产 → 403 FILE_ASSET.FORBIDDEN,反馈不落库。"""
|
||||||
|
def test_submit_rejects_non_image(app, client, user_headers):
|
||||||
|
"""ext='pdf' 的资产 → 400 FEEDBACK.IMAGE_INVALID。"""
|
||||||
|
def test_submit_rejects_referenced_asset(app, client, user_headers):
|
||||||
|
"""reference_count=1 的图片资产 → 400 FEEDBACK.IMAGE_INVALID(防挂已被业务引用资产)。"""
|
||||||
|
def test_submit_rejects_too_many(app, client, user_headers):
|
||||||
|
"""6 个 asset_no → 400 FEEDBACK.IMAGE_TOO_MANY,反馈不落库。"""
|
||||||
|
def test_submit_text_only_keeps_legacy(app, client, user_headers):
|
||||||
|
"""不带 image_asset_nos:200,general_feedback_images 零行(回归)。"""
|
||||||
|
```
|
||||||
|
|
||||||
|
省略体断言:非 2xx 时用 `parse_api_error(resp.get_json())["code"]` 断错误码,并断 `GeneralFeedbackImage.query.count() == 0`(拒绝路径不落任何行)。
|
||||||
|
|
||||||
|
- [ ] **Step 2: 运行确认失败**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd backend && python -m pytest tests/api/test_general_feedback_api.py -v
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected: FAIL/ERROR(接口忽略 `image_asset_nos`,断言 0 行失败)。
|
||||||
|
|
||||||
|
- [ ] **Step 3: 实现接口逻辑**
|
||||||
|
|
||||||
|
`handlers.py` 顶部模块常量与 import:
|
||||||
|
|
||||||
|
```python
|
||||||
|
_FEEDBACK_MAX_IMAGES = 5
|
||||||
|
_FEEDBACK_IMAGE_EXTENSIONS = {'png', 'jpg', 'jpeg', 'webp'}
|
||||||
|
```
|
||||||
|
|
||||||
|
import 增加 `GeneralFeedbackImage`(第 12 行 models import)与 `from app.services.file_assets.service import get_asset_for_user, mark_asset_referenced`。
|
||||||
|
|
||||||
|
`submit_general_feedback` 中,在现有 chat_log 校验之后、`row = GeneralFeedback(...)` 之前插入 `[STEP]` 注释分块(AGENTS.md §5.3):
|
||||||
|
|
||||||
|
1. 解析:`raw = data.get('image_asset_nos')`;非 list → `ValidationError(code='FEEDBACK.IMAGE_INVALID', message='image_asset_nos must be a list')`;元素转 str 去空白、去重(保序);`len > _FEEDBACK_MAX_IMAGES` → `ValidationError(code='FEEDBACK.IMAGE_TOO_MANY', message='最多附加 5 张图片')`。
|
||||||
|
2. 逐个校验(任一失败整单拒绝):`asset = get_asset_for_user(asset_no, user.id)`;`asset.extension not in _FEEDBACK_IMAGE_EXTENSIONS` → FEEDBACK.IMAGE_INVALID(message 注明仅支持图片);`asset.upload_status != 'ready'` → FEEDBACK.IMAGE_INVALID;`asset.reference_count != 0 or asset.lifecycle_status != 'temporary'` → FEEDBACK.IMAGE_INVALID(message 注明该文件已被使用)。通过者收集为 `assets: list[FileAsset]`。
|
||||||
|
3. 落库:`db.session.add(row)` → `db.session.flush()` 拿 `row.id` → 按枚举序 `GeneralFeedbackImage(feedback_id=row.id, asset_id=a.id, sort_order=idx)` → 逐个 `mark_asset_referenced(a)` → `try: db.session.commit() except IntegrityError: db.session.rollback(); raise ValidationError(code='FEEDBACK.IMAGE_INVALID', message='图片已被使用,请重新添加')`(并发双挂兜底,Review Focus 2;IntegrityError 已在文件头 import)。
|
||||||
|
4. 通知与返回不变(`send_feedback_group_notification(row, user)` 之后,`jsonify({'status': 'ok', 'id': row.id})`)。
|
||||||
|
|
||||||
|
- [ ] **Step 4: 同步错误码四语言**
|
||||||
|
|
||||||
|
`frontend/src/locales/{zh-CN,zh-TW,en,th}/errors.json` 的 codes 段(搜 `FILE_ASSET_INVALID_TYPE` 所在对象,同层追加):
|
||||||
|
|
||||||
|
- zh-CN:`"FEEDBACK_IMAGE_INVALID": "反馈图片无效或已被使用。"`,`"FEEDBACK_IMAGE_TOO_MANY": "反馈图片数量超过上限。"`,`"FEEDBACK_IMAGE_NOT_FOUND": "反馈图片不存在。"`
|
||||||
|
- zh-TW:`"FEEDBACK_IMAGE_INVALID": "迴饋圖片無效或已被使用。"`,`"FEEDBACK_IMAGE_TOO_MANY": "迴饋圖片數量超過上限。"`,`"FEEDBACK_IMAGE_NOT_FOUND": "迴饋圖片不存在。"`
|
||||||
|
- en:`"FEEDBACK_IMAGE_INVALID": "The feedback image is invalid or already in use."`,`"FEEDBACK_IMAGE_TOO_MANY": "Too many feedback images."`,`"FEEDBACK_IMAGE_NOT_FOUND": "Feedback image not found."`
|
||||||
|
- th:`"FEEDBACK_IMAGE_INVALID": "รูปภาพข้อเสนอแนะไม่ถูกต้องหรือถูกใช้งานแล้ว"`,`"FEEDBACK_IMAGE_TOO_MANY": "จำนวนรูปภาพข้อเสนอแนะเกินกำหนด"`,`"FEEDBACK_IMAGE_NOT_FOUND": "ไม่พบรูปภาพข้อเสนอแนะ"`
|
||||||
|
|
||||||
|
- [ ] **Step 5: 运行测试确认通过**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python -m pytest tests/api/test_general_feedback_api.py -v
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected: 6 个用例全 PASS。
|
||||||
|
|
||||||
|
- [ ] **Step 6: Commit**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git add backend/app/api/user/handlers.py backend/tests/api/test_general_feedback_api.py frontend/src/locales/
|
||||||
|
git commit -m "feat(feedback): 提交接口支持携带图片资产并校验引用"
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Task 3: 企微通知附图行(后端)
|
||||||
|
|
||||||
|
**Files:**
|
||||||
|
- Modify: `backend/app/services/feedback_notify.py`(`build_feedback_markdown`,93-135 行)
|
||||||
|
- Test: `backend/tests/services/test_feedback_notify.py`(新建)
|
||||||
|
|
||||||
|
**Interfaces:**
|
||||||
|
- Consumes: Task 1 的 `GeneralFeedback.images` relationship。
|
||||||
|
- Produces: markdown 在「反馈内容」段之前多一行 `>附图:{N} 张`(仅当 N>0)。消息其余行与顺序不变。
|
||||||
|
|
||||||
|
- [ ] **Step 1: 写失败测试**
|
||||||
|
|
||||||
|
```python
|
||||||
|
def test_markdown_includes_image_count(app):
|
||||||
|
"""有图反馈:markdown 含「附图:2 张」行;无图反馈:不含「附图」。"""
|
||||||
|
# app context 内建 GeneralFeedback + 2 条 GeneralFeedbackImage(feedback_id 指向它),commit;
|
||||||
|
# md = build_feedback_markdown(fb, None)
|
||||||
|
# assert "附图:2 张" in md;再建一条无图反馈断 "附图" not in 其 md
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 2: 运行确认失败**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python -m pytest tests/services/test_feedback_notify.py -v # Expected: FAIL(无附图行)
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 3: 实现**
|
||||||
|
|
||||||
|
`build_feedback_markdown` 中 `lines.extend(['', '**反馈内容:**', content or '-'])` 之前插入:
|
||||||
|
|
||||||
|
```python
|
||||||
|
image_count = len(feedback.images or [])
|
||||||
|
if image_count:
|
||||||
|
lines.append(f'>附图:{image_count} 张')
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 4: 运行确认通过** 同 Step 2 命令,Expected: PASS。
|
||||||
|
|
||||||
|
- [ ] **Step 5: Commit**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git add backend/app/services/feedback_notify.py backend/tests/services/test_feedback_notify.py
|
||||||
|
git commit -m "feat(feedback): 企微反馈通知增加附图数量行"
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Task 4: 报表行附图元数据 + 管理端图片代理接口(后端)
|
||||||
|
|
||||||
|
**Files:**
|
||||||
|
- Modify: `backend/app/services/admin/report_service.py:560-589`(`list_general_feedbacks_report`)与文件内新增函数
|
||||||
|
- Modify: `backend/app/api/admin/reports.py`(追加路由)
|
||||||
|
- Test: `backend/tests/api/test_general_feedback_api.py`(追加用例)
|
||||||
|
|
||||||
|
**Interfaces:**
|
||||||
|
- Consumes: Task 1 模型;现有 `read_asset_bytes(asset: FileAsset) -> bytes`(`service.py:623`,校验未删除/未过期)。
|
||||||
|
- Produces:
|
||||||
|
- `list_general_feedbacks_report` 每行新增 `images: list[dict]`,元素键恰为 `image_id, asset_no, original_filename, file_size, sort_order`(int/str/str/int/int),按 sort_order 升序;无图行 `images == []`。
|
||||||
|
- `report_service.get_general_feedback_image_payload(feedback_id: int, image_id: int) -> dict`,返回 `{'data': bytes, 'mime_type': str, 'filename': str}`;image 不存在或不属于该 feedback → `NotFoundError(code='FEEDBACK.IMAGE_NOT_FOUND', message='反馈图片不存在')`。
|
||||||
|
- 路由 `GET /api/admin/reports/general-feedbacks/<int:feedback_id>/images/<int:image_id>/raw`,`@require_admin`,响应为图片字节流:`Content-Type` = mime,`Content-Disposition: inline; filename*=UTF-8''<quote(filename)>`(`urllib.parse.quote`)。
|
||||||
|
|
||||||
|
- [ ] **Step 1: 写失败测试**(追加到 `test_general_feedback_api.py`)
|
||||||
|
|
||||||
|
```python
|
||||||
|
def test_report_rows_include_images(app, client, user_headers, admin_headers):
|
||||||
|
"""报表行含 images 元数据;无图行 images==[]。"""
|
||||||
|
# user 提交一条带 a1 的反馈 + 一条纯文本反馈;
|
||||||
|
# admin GET /api/admin/reports/general-feedbacks → 找到两行:
|
||||||
|
# 有图行 images[0] 键集合 == {"image_id","asset_no","original_filename","file_size","sort_order"} 且 asset_no==a1.asset_no;
|
||||||
|
# 无图行 images == []
|
||||||
|
|
||||||
|
def test_admin_image_raw_streams(app, client, user_headers, admin_headers, monkeypatch):
|
||||||
|
"""管理员经 raw 接口取到图片字节;错配 feedback_id → 404 FEEDBACK.IMAGE_NOT_FOUND;非管理员 → 403。"""
|
||||||
|
# monkeypatch app.services.file_assets.service.file_asset_storage.get_bytes = lambda key: b"\x89PNG\r\n\x1a\nfake"
|
||||||
|
# 提交一条带图反馈后:GET .../<fb_id>/images/<image_id>/raw → 200,data 匹配,content_type 以 "image/png" 开头
|
||||||
|
# GET .../<fb_id + 99999>/images/<同一 image_id>/raw → 404,parse_api_error code == FEEDBACK.IMAGE_NOT_FOUND
|
||||||
|
# 同接口换 user_headers → 403
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 2: 运行确认失败**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python -m pytest tests/api/test_general_feedback_api.py -v # Expected: 新用例 FAIL(无 images 键/404)
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 3: 实现 service 与路由**
|
||||||
|
|
||||||
|
`report_service.py`:import `GeneralFeedbackImage` 与 `from app.models import FileAsset`、`from app.services.file_assets.service import read_asset_bytes`。`list_general_feedbacks_report` 行构建后批量补 images:
|
||||||
|
|
||||||
|
```python
|
||||||
|
def _attach_general_feedback_images(rows: list[dict], feedback_ids: list[int]) -> None:
|
||||||
|
"""批量回填每行 images 元数据(单查询,按 sort_order 排序),无图行置空列表。"""
|
||||||
|
```
|
||||||
|
|
||||||
|
实现:单条 query `GeneralFeedbackImage` join `FileAsset`,`feedback_id.in_(feedback_ids)`,`order_by(sort_order, id)`,按 feedback_id 分组后写入各行。`list_general_feedbacks_report` 末尾调用它。
|
||||||
|
|
||||||
|
新增:
|
||||||
|
|
||||||
|
```python
|
||||||
|
def get_general_feedback_image_payload(feedback_id: int, image_id: int) -> dict:
|
||||||
|
"""读取反馈图片字节(管理端代理输出,不走 MinIO 预签名,见 spec D6)。"""
|
||||||
|
# GeneralFeedbackImage.filter_by(id=image_id, feedback_id=feedback_id).first() → 无则 FEEDBACK.IMAGE_NOT_FOUND
|
||||||
|
# asset = db.session.get(FileAsset, img.asset_id);asset 为 None 或 deleted_at 非空 → 同上
|
||||||
|
# data = read_asset_bytes(asset);返回 {'data': data, 'mime_type': asset.mime_type or 'application/octet-stream', 'filename': asset.original_filename}
|
||||||
|
```
|
||||||
|
|
||||||
|
`reports.py` 追加(import `Response`、`urllib.parse.quote`、`report_service` 已有):
|
||||||
|
|
||||||
|
```python
|
||||||
|
@admin_bp.route('/reports/general-feedbacks/<int:feedback_id>/images/<int:image_id>/raw', methods=['GET'])
|
||||||
|
@require_admin
|
||||||
|
def general_feedback_image_raw(feedback_id: int, image_id: int):
|
||||||
|
"""代理输出意见反馈截图字节流(inline 展示用)。"""
|
||||||
|
payload = report_service.get_general_feedback_image_payload(feedback_id, image_id)
|
||||||
|
resp = Response(payload['data'], mimetype=payload['mime_type'])
|
||||||
|
resp.headers['Content-Disposition'] = f"inline; filename*=UTF-8''{quote(payload['filename'])}"
|
||||||
|
return resp
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 4: 运行确认通过**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python -m pytest tests/api/test_general_feedback_api.py -v # Expected: 全部 PASS
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 5: Commit**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git add backend/app/services/admin/report_service.py backend/app/api/admin/reports.py backend/tests/api/test_general_feedback_api.py
|
||||||
|
git commit -m "feat(admin): 报表反馈行内附图元数据与图片代理接口"
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Task 5: 反馈弹窗 Element Plus 化 + 粘贴/选图上传(前端)
|
||||||
|
|
||||||
|
**Files:**
|
||||||
|
- Rewrite: `frontend/src/shared/components/GeneralFeedbackDialog.vue`
|
||||||
|
- Modify: `frontend/src/features/workspace/components/WorkspaceModals.vue`(移除 `:auth-headers` 绑定与未再使用的 `getAuthHeaders` import)
|
||||||
|
- Modify: `frontend/src/features/chat/components/ChatViewOverlays.vue`(同上)
|
||||||
|
- Modify: `frontend/src/features/workspace/pages/FeedbackPage.vue`(同上,若有绑定)
|
||||||
|
- Modify: `frontend/src/locales/{zh-CN,zh-TW,en,th}/feedback.json`(新增 `upload` 段)
|
||||||
|
|
||||||
|
**Interfaces:**
|
||||||
|
- Consumes: `uploadFileAsset(file: File): Promise<FileAssetResponse>`(`@/shared/api/file-assets.api.ts`,返回含 `asset_no`);`requestJson<T>(url, init)`(`@/shared/api/client`,自动附鉴权头,失败抛 `BusinessError`);现有 props `modelValue: boolean`、`sourcePage?: string`(默认 'unknown')、`chatLogId?: number | null`,emits `update:modelValue` / `submitted` **保持不变**(仅删除 `authHeaders`)。
|
||||||
|
- Produces: 提交 payload 新增 `image_asset_nos: string[]`(仅 `status==='ready'` 的图,按添加顺序)。i18n 键 `feedback.upload.*`。
|
||||||
|
|
||||||
|
- [ ] **Step 1: 四语言 `feedback.json` 增加 `upload` 段**
|
||||||
|
|
||||||
|
在 `submit` 键后追加(`zh-CN` 为准,其余三语言如下):
|
||||||
|
|
||||||
|
```json
|
||||||
|
"upload": {
|
||||||
|
"addImage": "添加图片",
|
||||||
|
"pasteHint": "支持粘贴截图(Ctrl+V)或点击添加,最多 5 张",
|
||||||
|
"maxCount": "最多添加 {count} 张图片",
|
||||||
|
"maxSize": "单张图片不能超过 {size}MB",
|
||||||
|
"invalidType": "仅支持 png / jpg / jpeg / webp 格式图片",
|
||||||
|
"uploadFailed": "图片上传失败,请重试",
|
||||||
|
"remove": "移除图片"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- zh-TW:`添加圖片` / `支援貼上截圖(Ctrl+V)或點擊新增,最多 5 張` / `最多新增 {count} 張圖片` / `單張圖片不能超過 {size}MB` / `僅支援 png / jpg / jpeg / webp 格式圖片` / `圖片上傳失敗,請重試` / `移除圖片`
|
||||||
|
- en:`Add images` / `Paste a screenshot (Ctrl+V) or click to add, up to 5` / `Up to {count} images` / `Each image must be within {size}MB` / `Only png / jpg / jpeg / webp images are supported` / `Image upload failed, please retry` / `Remove image`
|
||||||
|
- th:`เพิ่มรูปภาพ` / `วางภาพหน้าจอ (Ctrl+V) หรือคลิกเพื่อเพิ่ม สูงสุด 5 รูป` / `เพิ่มได้สูงสุด {count} รูป` / `รูปภาพเดียวต้องไม่เกิน {size}MB` / `รองรับเฉพาะไฟล์ png / jpg / jpeg / webp` / `อัปโหลดรูปภาพไม่สำเร็จ กรุณาลองอีกครั้ง` / `นำรูปภาพออก`
|
||||||
|
|
||||||
|
- [ ] **Step 2: 重写 `GeneralFeedbackDialog.vue`**
|
||||||
|
|
||||||
|
文件头块注释更新(用途/依赖:element-plus、file-assets.api、client/依赖关系)。要点:
|
||||||
|
|
||||||
|
- import 样式仿 `frontend/src/features/admin/modules/agents/AgentsPage.vue:14-23`:按需 `import { ElButton, ElDialog, ElInput, ElMessage, ElOption, ElSegmented, ElSelect } from 'element-plus'` + `import 'element-plus/dist/index.css'`(组件级导入,Vite 自动去重)。
|
||||||
|
- Props 删除 `authHeaders`;`visible = computed({ get: () => props.modelValue, set: (v) => emit('update:modelValue', v) })`。
|
||||||
|
- 模板:`<ElDialog v-model="visible" :title="t('feedback.title')" width="640px" append-to-body :close-on-click-modal="false">`;内容外层 `<div @paste="onPaste">`;类型用 `<ElSegmented :options="typeOptions" v-model="selectedType" />`;模块用 `ElSelect` + `ElOption v-for`;内容用 `<ElInput v-model="content" type="textarea" :rows="5" :maxlength="2000" show-word-limit resize="none" :placeholder="..." />`;底部 `ElButton`(取消)与 `ElButton type="primary" :loading="submitting"`(提交)。字数统计与错误行保留在输入框下方。
|
||||||
|
- 图片条(输入框下方):已添加图片渲染 48×48 缩略图(`:src="img.previewUrl"`,右上角小 × = `removeImage`,uploading 状态加半透明遮罩);末尾「添加图片」格子(Plus 图标 + `t('feedback.upload.addImage')`,点击触发隐藏 `<input type="file" multiple accept="image/png,image/jpeg,image/webp">`);下方灰色提示 `t('feedback.upload.pasteHint')`。
|
||||||
|
- 组件常量与逻辑(签名钉死):
|
||||||
|
|
||||||
|
```ts
|
||||||
|
const MAX_FEEDBACK_IMAGES = 5;
|
||||||
|
const MAX_FEEDBACK_IMAGE_SIZE_MB = 10;
|
||||||
|
const FEEDBACK_IMAGE_ACCEPT = ['image/png', 'image/jpeg', 'image/webp'];
|
||||||
|
|
||||||
|
interface PendingImage {
|
||||||
|
assetNo: string | null; // 上传成功后的 FA 编号
|
||||||
|
status: 'uploading' | 'ready';
|
||||||
|
previewUrl: string; // URL.createObjectURL(file)
|
||||||
|
filename: string;
|
||||||
|
}
|
||||||
|
const images = ref<PendingImage[]>([]);
|
||||||
|
const hasUploadingImage = computed(() => images.value.some((i) => i.status === 'uploading'));
|
||||||
|
const canSubmit = computed(() => content.value.trim().length > 0 && !submitting.value && !hasUploadingImage.value);
|
||||||
|
|
||||||
|
/** [AI 触发时机] 无 —— 纯 UI 交互:批量加入图片;超过上限整批拒绝并提示 maxCount(不截取前 N 张)。 */
|
||||||
|
async function addImages(files: File[]): Promise<void>
|
||||||
|
// 校验:先过滤类型不在 FEEDBACK_IMAGE_ACCEPT 的 → ElMessage.error(invalidType);
|
||||||
|
// 若 files.length + images.length > MAX_FEEDBACK_IMAGES → ElMessage.error(t('feedback.upload.maxCount', { count: MAX_FEEDBACK_IMAGES })) 且整批不入队;
|
||||||
|
// 单张 file.size > MAX_FEEDBACK_IMAGE_SIZE_MB * 1024 * 1024 → ElMessage.error(maxSize) 跳过该张;
|
||||||
|
// 逐张入队 status='uploading' → uploadFileAsset(file) 成功置 ready+assetNo;失败:移除该项 + ElMessage.error(uploadFailed)。
|
||||||
|
|
||||||
|
function removeImage(index: number): void // revoke previewUrl 后 splice
|
||||||
|
function onPaste(e: ClipboardEvent): void // e.clipboardData.items 中 kind==='file' 且 type 以 'image/' 开头的项 getAsFile();仅当取到文件才 preventDefault;调 addImages
|
||||||
|
function onFileChange(e: Event): void // input.files → addImages → input.value = ''
|
||||||
|
function cleanupImages(): void // 全部 revoke + 清空(resetForm 与弹窗关闭时调用,复用现有 watch(modelValue) 位置)
|
||||||
|
```
|
||||||
|
|
||||||
|
- 提交:`requestJson<void>('/api/user/feedback', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ feedback_type, feedback_module, content, source_page, ...(chatLogId != null ? { chat_log_id: chatLogId } : {}), image_asset_nos: images.value.filter(i => i.status === 'ready').map(i => i.assetNo as string) }) })`;捕获 `BusinessError` → `error.value = e.message`(沿用现有内联错误展示);成功路径不变(`emit('submitted'); closeDialog()`)。
|
||||||
|
- 其余行为保持:类型/模块仍存**翻译后的展示文案**;语言切换时 resetForm 的 watch 保留(cleanupImages 一并调用)。
|
||||||
|
|
||||||
|
- [ ] **Step 3: 更新三个挂载点**
|
||||||
|
|
||||||
|
在 `WorkspaceModals.vue`、`ChatViewOverlays.vue`、`FeedbackPage.vue` 中删除传给 `GeneralFeedbackDialog` 的 `:auth-headers="getAuthHeaders()"`(属性名以实际文件为准);若 `getAuthHeaders` 在该文件无其他使用,连同 import 一并删除。
|
||||||
|
|
||||||
|
- [ ] **Step 4: 构建验证**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd frontend && npm run build
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected: 构建通过,无 TS 报错;grep 确认 `GeneralFeedbackDialog.vue` 内无 `btn-`/`input-field`/`<textarea`/`<select`。
|
||||||
|
|
||||||
|
- [ ] **Step 5: 人工验证(dev server)**
|
||||||
|
|
||||||
|
`npm run dev` 后:粘贴一张截图 → 缩略图出现;粘贴 6 张 → maxCount 提示;删除、提交成功;workspace 与 chat 两个入口弹窗均可开、提交成功(chat 入口带 chat_log_id)。暗色主题下弹窗可读。
|
||||||
|
|
||||||
|
- [ ] **Step 6: Commit**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git add frontend/src/shared/components/GeneralFeedbackDialog.vue frontend/src/features/workspace/components/WorkspaceModals.vue frontend/src/features/chat/components/ChatViewOverlays.vue frontend/src/features/workspace/pages/FeedbackPage.vue frontend/src/locales/
|
||||||
|
git commit -m "feat(feedback): 反馈弹窗整页替换 Element Plus 并支持粘贴与选图上传"
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Task 6: 管理端报表附图缩略图与大图预览(前端)
|
||||||
|
|
||||||
|
**Files:**
|
||||||
|
- Modify: `frontend/src/features/admin/api/admin.api.ts`(类型)
|
||||||
|
- Modify: `frontend/src/features/admin/modules/reports/composables/useReportsAdmin.ts`
|
||||||
|
- Modify: `frontend/src/features/admin/modules/reports/ReportsPage.vue`
|
||||||
|
|
||||||
|
**Interfaces:**
|
||||||
|
- Consumes: Task 4 的行内 `images` 元数据与 raw 接口;现有 `requestBlob(url)`(`@/shared/api/client`,自动附鉴权头,返回 `{ blob, filename? }`)。
|
||||||
|
- Produces(在 `useReportsAdmin` 返回对象中新增,供 ReportsPage 解构):
|
||||||
|
- `feedbackImagePreview: Ref<{ feedbackId: number; images: FeedbackReportImage[]; index: number } | null>`
|
||||||
|
- `feedbackImageUrl(feedbackId: number, imageId: number): string | null`(objectURL 缓存,键 `${feedbackId}:${imageId}`,未加载过返回 null)
|
||||||
|
- `loadFeedbackImage(feedbackId: number, imageId: number): Promise<void>`(缓存键 `${feedbackId}:${imageId}` 已存在时直接 return;否则 `requestBlob('/api/admin/reports/general-feedbacks/${feedbackId}/images/${imageId}/raw')` → `URL.createObjectURL(blob)` 入缓存;失败静默置缓存值为 `''` 表示占位)
|
||||||
|
- `openFeedbackImagePreview(row: any, index: number): void` / `closeFeedbackImagePreview(): void` / `stepFeedbackImagePreview(delta: number): void`(index 在 images 内循环)
|
||||||
|
- 类型:`interface FeedbackReportImage { image_id: number; asset_no: string; original_filename: string; file_size: number; sort_order: number }`(放 admin.api.ts 并导出);报表行类型加可选 `images?: FeedbackReportImage[]`。
|
||||||
|
|
||||||
|
- [ ] **Step 1: composable 改造**
|
||||||
|
|
||||||
|
1. `visibleReportKeys` 的 `feedbackFixedOrder`(1068-1079 行)在 `'content'` 后插入 `'images'`。
|
||||||
|
2. 现有按列名返回宽度的 switch(useReportsAdmin.ts 顶部,`default: return 160;` 处)加 `case 'images': return 176;`。
|
||||||
|
3. `feedbackReportI18nMap` 四个语言包的 `generalColumns` 各加一条(en/zh-CN/zh-TW/th):`images: 'Images'` / `images: '附图'` / `images: '附圖'` / `images: 'รูปภาพ'`(CJK 沿用文件内已有的 `\uXXXX` 转义风格)。
|
||||||
|
4. 新增 Interfaces 段列出的状态与五个函数(含 objectURL 缓存 `Map<string, string>`,模块级或 composable 闭包内)。
|
||||||
|
|
||||||
|
- [ ] **Step 2: ReportsPage 单元格与 lightbox**
|
||||||
|
|
||||||
|
1. 意见反馈内容列旁新增分支(1417 行的 `<template v-if=...>` 链中,chat_log_id 分支之前):
|
||||||
|
|
||||||
|
```html
|
||||||
|
<template v-else-if="isMergedFeedbackTable && feedbackTab === 'general' && key === 'images'">
|
||||||
|
<div class="flex items-center gap-1" :style="getReportCellInnerStyle()">
|
||||||
|
<template v-if="(row.images || []).length">
|
||||||
|
<img
|
||||||
|
v-for="(img, i) in row.images"
|
||||||
|
:key="img.image_id"
|
||||||
|
:src="feedbackImageUrl(row.id, img.image_id) || ''"
|
||||||
|
:alt="img.original_filename"
|
||||||
|
loading="lazy"
|
||||||
|
class="h-10 w-10 cursor-pointer rounded border border-default object-cover"
|
||||||
|
@load="loadFeedbackImage(row.id, img.image_id)"
|
||||||
|
@error="loadFeedbackImage(row.id, img.image_id)"
|
||||||
|
@click.stop="openFeedbackImagePreview(row, i)"
|
||||||
|
/>
|
||||||
|
</template>
|
||||||
|
<span v-else class="text-muted">-</span>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
```
|
||||||
|
|
||||||
|
(`@load`/`@error` 触发懒加载:src 为空时浏览器立即 error → 发起 blob 加载,加载完成后缓存更新触发重渲;`<img>` 无法自带鉴权头,故必须走 blob,见 spec D6。)
|
||||||
|
|
||||||
|
2. 该单元格的 `:title` 绑定(1413 行)把 `key === 'images'` 加入置 undefined 的条件,避免 title 出现 `[object Object]`。
|
||||||
|
3. 表格之后(仿 1523-1543 行 chat-logs 详情 overlay 的自建模式)新增 lightbox:
|
||||||
|
|
||||||
|
```html
|
||||||
|
<div v-if="feedbackImagePreview" class="fixed inset-0 z-50 flex items-center justify-center p-4">
|
||||||
|
<div class="absolute inset-0 bg-black/70" @click="closeFeedbackImagePreview"></div>
|
||||||
|
<div class="relative flex max-h-[90vh] max-w-[90vw] flex-col items-center gap-3">
|
||||||
|
<div class="flex items-center gap-4">
|
||||||
|
<button type="button" class="btn-icon-ds text-white" @click.stop="stepFeedbackImagePreview(-1)">‹</button>
|
||||||
|
<img v-if="currentPreviewUrl" :src="currentPreviewUrl" :alt="currentPreviewImage?.original_filename" class="max-h-[80vh] max-w-[80vw] rounded object-contain" />
|
||||||
|
<button type="button" class="btn-icon-ds text-white" @click.stop="stepFeedbackImagePreview(1)">›</button>
|
||||||
|
</div>
|
||||||
|
<div class="flex items-center gap-3 text-sm text-white/80">
|
||||||
|
<span>{{ feedbackImagePreview.index + 1 }} / {{ feedbackImagePreview.images.length }}</span>
|
||||||
|
<span>{{ currentPreviewImage?.original_filename }}</span>
|
||||||
|
<button type="button" class="btn-icon-ds" :title="t('admin.report.feedback.closePreview')" @click="closeFeedbackImagePreview">✕</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
```
|
||||||
|
|
||||||
|
`currentPreviewImage` / `currentPreviewUrl` 为 ReportsPage 内基于 `feedbackImagePreview` 与 `feedbackImageUrl` 的 computed;打开与翻页时对当前图调用 `loadFeedbackImage`。多图时(仅 1 张也显示,翻页按钮按 images.length 循环)。
|
||||||
|
|
||||||
|
4. `admin.json` 四语言 `report.feedback` 段加 `"closePreview"`:zh-CN `关闭预览` / zh-TW `關閉預覽` / en `Close preview` / th `ปิดตัวอย่าง`。
|
||||||
|
|
||||||
|
- [ ] **Step 3: 构建验证**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd frontend && npm run build # Expected: 通过
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 4: 人工验证**
|
||||||
|
|
||||||
|
后端起 dev 服务(需 `flask db upgrade` 到新 head),提交 1-2 条带图反馈后,管理端「报表 → 用户反馈」:有图行显示缩略图,点击放大、左右翻页、关闭;无图行显示 `-`;Network 面板确认无图行零图片请求、缩略图 lazy(Review Focus 3/4)。
|
||||||
|
|
||||||
|
- [ ] **Step 5: Commit**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git add frontend/src/features/admin/
|
||||||
|
git commit -m "feat(admin): 报表意见反馈页签展示附图缩略图与大图预览"
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Task 7: 文档同步与收尾验证
|
||||||
|
|
||||||
|
**Files:**
|
||||||
|
- Modify: `docs/funclist.md`(意见反馈相关条目)
|
||||||
|
- Modify: `docs/superpowers/specs/2026-10-26-feedback-image-attachment-design.md`(状态行改为「已实现」)
|
||||||
|
|
||||||
|
- [ ] **Step 1: 更新 `funclist.md`**
|
||||||
|
|
||||||
|
在功能清单中「意见反馈」所在小节补一行(保持该文件既有格式):`意见反馈支持粘贴/上传截图附件(≤5 张),管理端报表可查看附图与大图预览`。若清单中无意见反馈条目,则在用户端与管理端各自最贴近的位置各补一条。
|
||||||
|
|
||||||
|
- [ ] **Step 2: 全量验证**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd backend && python -m pytest tests/api/test_general_feedback_api.py tests/services/test_feedback_notify.py -v # Expected: 全 PASS
|
||||||
|
cd ../frontend && npm run build # Expected: 通过
|
||||||
|
cd .. && flask db heads # (backend venv)Expected: 单 head
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 3: Commit**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git add docs/funclist.md docs/superpowers/specs/2026-10-26-feedback-image-attachment-design.md
|
||||||
|
git commit -m "docs(funclist): 补充意见反馈截图附件功能项"
|
||||||
|
```
|
||||||
@@ -0,0 +1,186 @@
|
|||||||
|
# 意见反馈支持截图附件 — 设计文档
|
||||||
|
|
||||||
|
- 日期:2026-10-26
|
||||||
|
- 分支:`picture-feedback`(自 `dev` 切出,当前为空分支)
|
||||||
|
- 状态:已实现(2026-10-26,分支 picture-feedback)
|
||||||
|
- 需求来源:用户反馈处理时经常缺少截图,无法复现问题;现反馈弹窗只支持纯文本。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. 意图与背景
|
||||||
|
|
||||||
|
意见反馈弹窗(`GeneralFeedbackDialog.vue`)目前只能提交文字(反馈类型/模块/内容/来源页),处理人拿到反馈后经常因为"没有截图、无法复现"反复找提交人确认。本次为反馈增加**截图附件**:用户在弹窗里可以**粘贴(Ctrl+V)**或**点击选图**添加截图,提交后图片随反馈入库;处理人在**管理端报表页**查看反馈时可以看到缩略图并点开大图。
|
||||||
|
|
||||||
|
处理人现有两个入口:企微群机器人通知(文字摘要)+ 后台报表完整记录。**已与需求方确认(方案 1)**:图片只在后台报表查看,企微通知保持纯文字。
|
||||||
|
|
||||||
|
## 2. 目标 / 非目标 / 反目标
|
||||||
|
|
||||||
|
**目标**
|
||||||
|
- 用户弹窗支持粘贴截图 + 点击选图,带缩略图预览与单张删除。
|
||||||
|
- 提交后图片与反馈记录关联,管理端报表「用户反馈」页签可见缩略图、可放大查看、可前后翻图。
|
||||||
|
- 有图时企微通知多一行「附图:N 张」(纯文字,不发图)。
|
||||||
|
- 反馈弹窗整页替换为 Element Plus 控件(需求方已拍板)。
|
||||||
|
|
||||||
|
**非目标(本期不做)**
|
||||||
|
- 企微群消息内嵌图片(企微机器人 markdown 不支持外链图,image 消息单张 ≤2MB,群里会刷屏)。
|
||||||
|
- 服务端图片压缩/旋转/加水印。
|
||||||
|
- 拖拽上传(粘贴 + 点选已覆盖需求)。
|
||||||
|
- gif/bmp 格式(平台文件资产白名单本就不含)。
|
||||||
|
- 提交后增删图片;反馈提交后即不可变。
|
||||||
|
- 关闭反馈时释放图片资产(图片随反馈长期保留)。
|
||||||
|
- 用户侧"我的反馈"回看页面(现网无此入口)。
|
||||||
|
- 管理端 ReportsPage 其余部分的 Element Plus 化(只加展示,不整页替换)。
|
||||||
|
|
||||||
|
**反目标(出现即算失败)**
|
||||||
|
- 破坏现有纯文本反馈的提交链路与 SSE 对话链路。
|
||||||
|
- 未引用图片滞留:孤儿图必须能被现有 72h 清理任务回收,不允许出现"永久滞留的临时资产"。
|
||||||
|
- 同一页面混用两套控件风格(仓库红线)。
|
||||||
|
|
||||||
|
## 3. 约束(来自 AGENTS.md / 现有设施)
|
||||||
|
|
||||||
|
1. **改表必须配套 Alembic 迁移**(当前单 head:`mh23e4f5a6b7`)。
|
||||||
|
2. **前端统一 Element Plus**:弹窗整页替换;管理端 ReportsPage 保持原样,只允许新增 `<img>` 缩略图与自建 overlay 预览(展示型,不新增表单控件)。
|
||||||
|
3. **HTTP 统一 `requestJson`(`@/shared/api/client`)**:弹窗现为裸 `fetch`,本次替换为 `requestJson`;失败以 `BusinessError` + `useMessage()` 展示。**后端接口响应契约保持现状**(`{status:'ok', id}`,唯一消费方就是本弹窗),不强行改 envelope,控制改动面。
|
||||||
|
4. **新增 error.code 同步四语言 `locales/*/errors.json`**。
|
||||||
|
5. **i18n 四语言**:新增文案补齐 zh-CN / zh-TW / en / th,禁止硬编码中文。
|
||||||
|
6. **不新增第三方依赖**:粘贴/上传/预览全部用现有依赖(原生 API + Element Plus + 现有 composables)。
|
||||||
|
7. **注释三层标准**(§5):文件层块注释 + 核心函数注释(含 AI 触发时机如有)+ `[STEP]` 分块。
|
||||||
|
8. **文档同步**:`docs/funclist.md` 与本设计文档随功能同一 PR 更新。
|
||||||
|
|
||||||
|
## 4. 已定决策
|
||||||
|
|
||||||
|
| # | 决策 | 来源 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| D1 | 图片只在管理端报表查看;企微通知纯文字,有图时加「附图:N 张」行 | 需求方(方案 1) |
|
||||||
|
| D2 | 反馈弹窗整页替换为 Element Plus | 需求方 |
|
||||||
|
| D3 | 选图/粘贴后**立即**上传(复用 `POST /api/files/assets` + `uploadFileAsset`),提交时 JSON 携带 `image_asset_nos[]`;取消弹窗的孤儿图交给现有 72h 清理,不新做回收 | 设计默认 |
|
||||||
|
| D4 | 限制:每条反馈最多 **5 张**,单张 **10MB**,格式 png/jpg/jpeg/webp;客户端校验 + **服务端扩展名二次校验**(平台资产白名单还含 pdf/doc 等文档类型,不能依赖) | 设计默认(可调) |
|
||||||
|
| D5 | 新子表 `general_feedback_images` 关联 feedback↔file_asset;`asset_id` 唯一约束(一张图只能挂一条反馈);提交时同事务调 `mark_asset_referenced` | 设计默认(照搬 `ShippingOrderIntake.asset_id` 模式) |
|
||||||
|
| D6 | 图片统一由**后端代理输出**:新增管理端 raw 接口流式返回图片字节,前端带鉴权头 fetch 取 blob 后 `URL.createObjectURL` 展示。**不走 MinIO 预签名 URL**——已核实:`presigned_get_url` 按 `MINIO_ENDPOINT` 签名(storage.py:32,123),`MINIO_PUBLIC_BASE_URL`(settings.py:674)全库无一处使用,生产 `MINIO_ENDPOINT=host.docker.internal:9000` 浏览器不可解析;且 SigV4 签名覆盖 Host,事后改写域名即失效 | 评审修订 |
|
||||||
|
| D7 | 大图预览:ReportsPage 内按该页现有自建 overlay 风格做轻量 lightbox(深色遮罩 + 大图 + 前后翻页);不复用 `FilePreviewModal`(其绑死 chat agent 取流) | 设计默认 |
|
||||||
|
| D8 | 提交接口 `POST /api/user/feedback` 响应契约不变,只扩展请求字段与校验 | 设计默认 |
|
||||||
|
| D9 | 仅允许挂载**全新未引用**资产:`reference_count == 0` 且 `lifecycle_status == 'temporary'`。防止把已投入其他业务(如货代接单)的资产挂到反馈上,污染其引用计数/生命周期 | 评审修订 |
|
||||||
|
| D10 | 缩略图以 `loading="lazy"` 按需加载原图,不做服务端缩略图生成;无图行零图片请求。列表默认 200 行,有图反馈占比低,可接受 | 评审确认 |
|
||||||
|
|
||||||
|
## 5. 方案详述
|
||||||
|
|
||||||
|
### 5.1 数据模型与迁移
|
||||||
|
|
||||||
|
新表 `general_feedback_images`:
|
||||||
|
|
||||||
|
| 列 | 类型 | 说明 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| id | Integer PK | |
|
||||||
|
| feedback_id | FK `general_feedbacks.id`,NOT NULL,indexed | 级联删除随反馈 |
|
||||||
|
| asset_id | FK `file_assets.id`,NOT NULL,**unique** | 一图只挂一条反馈 |
|
||||||
|
| sort_order | Integer,NOT NULL,default 0 | 按添加顺序 |
|
||||||
|
| created_at | DateTime,default utcnow | |
|
||||||
|
|
||||||
|
模型 `GeneralFeedbackImage` 放在 `backend/app/models/chat.py`(`GeneralFeedback` 旁),并在 `GeneralFeedback` 上加 `images` 有序 relationship。Alembic 迁移基于单 head `mh23e4f5a6b7`。
|
||||||
|
|
||||||
|
### 5.2 上传链路(用户弹窗)
|
||||||
|
|
||||||
|
1. 交互:内容输入框下方新增图片条——缩略图(右上角 × 删除)+「添加图片」格子;提示文案"支持粘贴截图(Ctrl+V)或点击添加,最多 5 张"。
|
||||||
|
2. 粘贴:监听弹窗根节点 `paste` 事件,`clipboardData.items` 中 `type startsWith 'image/'` 的项转 `File`;仅当存在图片项时拦截默认行为。
|
||||||
|
3. 选图:隐藏 `<input type="file" multiple accept="image/png,image/jpeg,image/webp">` 由格子触发。
|
||||||
|
4. 客户端校验:格式(扩展名/ mime)、单张 ≤10MB、总数 ≤5(含上传中与已上传);超限给出 i18n 提示。
|
||||||
|
5. 校验通过立即 `uploadFileAsset(file)`(`frontend/src/shared/api/file-assets.api.ts`),格子显示上传中态;失败可重试或移除。
|
||||||
|
6. 弹窗内维护 `uploadedAssets: [{assetNo, filename, previewUrl?, ...}]`。**取消/关闭弹窗不回收资产**:未提交的图是 `temporary` 状态,72h 后被 `SCH-FILE-ASSET-CLEANUP` 每小时任务自动清理(见 `services/file_assets/cleanup.py`),本期不主动调 `release_asset_reference`。
|
||||||
|
7. 缩略图预览优先用 `URL.createObjectURL`,弹窗关闭时 revoke。
|
||||||
|
|
||||||
|
### 5.3 提交接口变更(后端)
|
||||||
|
|
||||||
|
`POST /api/user/feedback`(`backend/app/api/user/handlers.py:122-177` `submit_general_feedback`):
|
||||||
|
|
||||||
|
- 请求体新增可选 `image_asset_nos: string[]`(≤5 个,去重)。
|
||||||
|
- 校验(任一失败整单拒绝,400):每个 asset_no 存在、`owner_user_id == 当前用户`、`upload_status` 为已上传、`deleted_at IS NULL`、扩展名 ∈ {png, jpg, jpeg, webp}(服务端二次校验,见 D4)、`reference_count == 0` 且 `lifecycle_status == 'temporary'`(未被任何业务引用,见 D9;`asset_id` 唯一约束兜底并发双挂)。
|
||||||
|
- 同一事务:创建 `GeneralFeedback` → 批量创建 `GeneralFeedbackImage`(sort_order 按传入顺序)→ 对每个资产调 `mark_asset_referenced`(`services/file_assets/service.py:430`,reference_count+1、lifecycle='referenced'、清 expires_at)→ commit。
|
||||||
|
- 失败路径:校验失败不落任何数据;commit 异常整体回滚。
|
||||||
|
- 响应契约不变:`{status:'ok', id}`。
|
||||||
|
- 错误码走 `AppError` 子类,新增 `FEEDBACK.IMAGE_INVALID` 之类错误码并同步四语言 `errors.json`。
|
||||||
|
|
||||||
|
### 5.4 企微通知调整
|
||||||
|
|
||||||
|
`backend/app/services/feedback_notify.py` `build_feedback_markdown`:仅当 `feedback.images` 非空时,在「反馈内容」前插入一行 `>附图:N 张`(N 为图片数)。不发送图片本体,其余不变。
|
||||||
|
|
||||||
|
### 5.5 管理端列表与图片查看
|
||||||
|
|
||||||
|
**后端**(`backend/app/api/admin/reports.py` + `services/admin/report_service.py`):
|
||||||
|
|
||||||
|
- `list_general_feedbacks_report`(report_service.py:560-590)每行新增 `images: [{image_id, asset_no, original_filename, file_size, sort_order}]`(仅元数据,不含 URL)。
|
||||||
|
- 新接口 `GET /api/admin/reports/general-feedbacks/<feedback_id>/images/<image_id>/raw`:鉴权沿用该 blueprint 现有管理员校验;校验 image 属于该 feedback;`read_asset_bytes` 读字节后流式输出,`Content-Type` 取资产 mime,`Content-Disposition: inline`。前端以带鉴权头的 fetch 取 blob 再 `URL.createObjectURL` 展示(见 D6,不使用预签名 URL,`<img>` 无需自带鉴权头)。
|
||||||
|
|
||||||
|
**前端**(`frontend/src/features/admin/modules/reports/`):
|
||||||
|
|
||||||
|
- `useReportsAdmin.ts` `feedbackFixedOrder`(1070-1083)在 `content` 后插入 `images` 虚拟列;API 类型(`admin.api.ts:856` 附近)同步。
|
||||||
|
- `ReportsPage.vue`:`images` 列渲染缩略图(`<img loading="lazy">`,高约 40px,最多 5 张横向排列),无图显示 `-`,blob 加载失败显示占位。
|
||||||
|
- 点击缩略图打开本页内 lightbox overlay(参照 chat-logs 详情 overlay 的自建模式,ReportsPage.vue:1524-1543):深色遮罩 + 居中大图 + 左右翻页(在该反馈 images 内循环)+ 关闭;打开与翻页时按需 fetch blob,关闭/切换时 revoke 旧 objectURL。
|
||||||
|
- 不改动该页其余控件风格。
|
||||||
|
|
||||||
|
### 5.6 反馈弹窗 Element Plus 化
|
||||||
|
|
||||||
|
`frontend/src/shared/components/GeneralFeedbackDialog.vue` 整页重写:
|
||||||
|
|
||||||
|
- 控件:`el-dialog` + `el-radio-group`/`el-segmented`(反馈类型三选一)+ `el-select`(反馈模块)+ `el-input type="textarea"`(maxlength 2000, show-word-limit)+ `el-button`(取消/提交,提交 loading 态)。图片条可用 `el-upload` 的 list-type="picture-card" 思路或自绘缩略图条(允许:上传区不是表单校验控件;实现者按 EP 惯例选择,但**禁止**再引入 `btn-*`/`input-field` 等旧类)。
|
||||||
|
- 现有行为保持:类型/模块取值仍是**翻译后的展示文案**(后端按 ≤32 字符字符串存储,本次不改该契约);`source-page`、`chat_log_id`(chat 来源时)透传;成功/失败提示文案沿用 `feedback.*` i18n。
|
||||||
|
- 提交改走 `requestJson`(已核实其自动附带鉴权头),移除 `auth-headers` prop,同步更新挂载点:`features/workspace/components/WorkspaceModals.vue`、`features/chat/components/ChatViewOverlays.vue`、`features/workspace/pages/FeedbackPage.vue`。
|
||||||
|
- Element Plus 引入方式参照 `features/admin/modules/agents/AgentsPage.vue`(手动按需 import + `element-plus/dist/index.css`;注意弹窗挂在 workspace/chat 场景下的样式与暗色主题表现)。
|
||||||
|
- 上传/粘贴中禁用提交按钮,防止图片未传完就提交。
|
||||||
|
|
||||||
|
### 5.7 i18n
|
||||||
|
|
||||||
|
- `frontend/src/locales/{zh-CN,zh-TW,en,th}/feedback.json`:新增 `upload.*`(addImage、pasteHint、maxCount、maxSize、invalidType、uploadFailed、remove 等)。
|
||||||
|
- `frontend/src/locales/{...}/admin.json`:`admin.report.feedback.images`(附图列头)与预览相关文案。
|
||||||
|
- `frontend/src/locales/{...}/errors.json`:新增图片校验错误码。
|
||||||
|
|
||||||
|
### 5.8 测试
|
||||||
|
|
||||||
|
- 后端 pytest(新增,无既有反馈测试可依):
|
||||||
|
- 提交带 `image_asset_nos`:资产被引用(reference_count+1、lifecycle='referenced'、expires_at 清空),图片行 sort_order 正确;
|
||||||
|
- 拒绝场景:他人资产、不存在的 asset_no、超过 5 张、重复 asset_no;
|
||||||
|
- 管理端 raw 图片接口:管理员可取且 Content-Type 正确、image 与 feedback 不匹配 404、非管理员被拒;
|
||||||
|
- 拒绝非图片扩展名资产(如 pdf);
|
||||||
|
- 拒绝已被其他业务引用的资产(reference_count > 0);
|
||||||
|
- 报表行内含 `images` 元数据数组。
|
||||||
|
- 既有链路回归:纯文本提交不受影响。
|
||||||
|
- 前端:弹窗无既有 spec,本期不强制新增(可选)。
|
||||||
|
|
||||||
|
## 6. 现有代码坐标(调研结论)
|
||||||
|
|
||||||
|
| 事物 | 位置 |
|
||||||
|
| --- | --- |
|
||||||
|
| 反馈弹窗组件 | `frontend/src/shared/components/GeneralFeedbackDialog.vue`(裸 fetch 提交 98-105 行) |
|
||||||
|
| 弹窗挂载点 | `features/workspace/components/WorkspaceModals.vue:9,122-128`;`features/chat/components/ChatViewOverlays.vue:8,53-54`;状态 `useChatPageDialogs.ts:81`、`useWorkspaceNavigation.ts:63,92,198`;占位路由 `features/workspace/pages/FeedbackPage.vue` |
|
||||||
|
| 提交接口 | `backend/app/api/user/handlers.py:122-177`(校验 feedback_type/module ≤32、content ≤2000、chat_log_id 归属) |
|
||||||
|
| 反馈模型 | `backend/app/models/chat.py:117-140` `GeneralFeedback`(无任何附件字段) |
|
||||||
|
| 企微通知 | `backend/app/services/feedback_notify.py`(markdown 组装 :93,发送 :138,best-effort) |
|
||||||
|
| 管理端路由/服务 | `backend/app/api/admin/reports.py:90-132`;`backend/app/services/admin/report_service.py:560-590` |
|
||||||
|
| 管理端页面 | `frontend/src/features/admin/modules/reports/ReportsPage.vue`(内容 popover :1417-1441;chat-logs 自建 overlay :1524-1543);`composables/useReportsAdmin.ts`(列序 :1070-1083);API `features/admin/api/admin.api.ts:856,888-912` |
|
||||||
|
| 文件资产模型 | `backend/app/models/file_asset.py:22-70`(`owner_user_id`、`lifecycle_status` temporary/referenced/expired、`reference_count`、`expires_at`) |
|
||||||
|
| 文件资产服务 | `backend/app/services/file_assets/service.py`(白名单 :55-58 含 png/jpg/jpeg/webp;序列化 :102-116;**owner-only** :119-136;30MB 限制 :155-157;`mark_asset_referenced` :430;`release_asset_reference` :450);存储 `storage.py`(预签名下载) |
|
||||||
|
| 上传接口(复用) | `POST /api/files/assets`(`backend/app/api/files/assets.py:33-49`,multipart);前端 `frontend/src/shared/api/file-assets.api.ts:24-31` `uploadFileAsset` |
|
||||||
|
| 预签名 URL 风险(已核实) | `storage.py:32` MinIO 客户端以 `MINIO_ENDPOINT` 构建、`:123` `presigned_get_url` 按其签名;`MINIO_PUBLIC_BASE_URL`(settings.py:674)全库未被使用;生产 `MINIO_ENDPOINT=host.docker.internal:9000` 浏览器不可解析 → 反馈图片不走预签名(D6) |
|
||||||
|
| 孤儿清理 | `backend/app/services/file_assets/cleanup.py`(72h TTL,每小时 `SCH-FILE-ASSET-CLEANUP`) |
|
||||||
|
| 关联模式参照 | `backend/app/models/shipping.py:250` `ShippingOrderIntake.asset_id` FK→file_assets |
|
||||||
|
| Element Plus 引入范例 | `App.vue:11-15`(ElConfigProvider);`features/admin/modules/agents/AgentsPage.vue:21-23`(手动 import + css) |
|
||||||
|
| i18n 注册 | `frontend/src/locales/index.ts:45-48`(namespace `feedback`);四语言 `locales/*/feedback.json`、`admin.json`、`errors.json` |
|
||||||
|
| Alembic | 单 head `mh23e4f5a6b7`(385 个 revision) |
|
||||||
|
| 不复用项 | `shared/components/FilePreviewModal.vue`(取流绑死 chat agent,需 agentId) |
|
||||||
|
|
||||||
|
## 7. 留给实现者的开放点(builder's call)
|
||||||
|
|
||||||
|
1. Element Plus 样式引入位置(组件级 vs 全局)与暗色主题验证。
|
||||||
|
2. raw 接口流式响应细节(Content-Disposition 的 UTF-8 文件名编码、缓存头)按后端既有流式惯例实现。
|
||||||
|
3. 图片条实现选 `el-upload` picture-card 还是自绘缩略条(前提:不违反红线 2)。
|
||||||
|
4. 粘贴事件监听目标与输入法/占位符的边界行为。
|
||||||
|
5. 错误码具体命名(遵循 `errors.json` 既有风格)。
|
||||||
|
|
||||||
|
## 8. 验收标准
|
||||||
|
|
||||||
|
1. 弹窗内可粘贴截图与点击选图;实时缩略图、可删除;超 5 张 / 超 10MB / 格式不符有明确提示(四语言)。
|
||||||
|
2. 提交成功后,图片与反馈关联入库;资产 `lifecycle='referenced'`,不会被 72h 清理回收。
|
||||||
|
3. 管理端「用户反馈」页签可见附图缩略图,点开可大图查看并前后翻页;旧的无图反馈展示不受影响;缩略图懒加载,无图行不发起图片请求。
|
||||||
|
4. 有图反馈的企微通知多一行「附图:N 张」;无图反馈通知与现状完全一致。
|
||||||
|
5. 取消弹窗未提交的图片 72h 后被现有清理任务回收。
|
||||||
|
6. `flask db upgrade` 可从单 head 平滑迁移;`npm run build` 通过;后端 pytest 全绿;纯文本反馈回归无影响。
|
||||||
|
7. `docs/funclist.md` 已同步更新。
|
||||||
@@ -912,6 +912,30 @@ export const closeAdminGeneralFeedback = (feedbackId: number) =>
|
|||||||
`/api/admin/reports/general-feedbacks/${feedbackId}/close`,
|
`/api/admin/reports/general-feedbacks/${feedbackId}/close`,
|
||||||
{ method: 'POST', ...auth() },
|
{ method: 'POST', ...auth() },
|
||||||
);
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 意见反馈附图元数据(管理端报表行内嵌)。
|
||||||
|
* 图片二进制不走预签名 URL,统一经 `/images/<image_id>/raw` 代理接口(requestBlob 附鉴权头)拉取。
|
||||||
|
*/
|
||||||
|
export interface FeedbackReportImage {
|
||||||
|
image_id: number;
|
||||||
|
asset_no: string;
|
||||||
|
original_filename: string;
|
||||||
|
file_size: number;
|
||||||
|
sort_order: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 意见反馈报表行(general_feedbacks)。
|
||||||
|
* 说明:通用报表接口历史上一律以 any 行返回,无显式行类型;此处固化意见反馈行的关键字段供
|
||||||
|
* 前端(useReportsAdmin 附图预览等)按类型消费;`images` 为可选字段以兼容旧数据与无图行。
|
||||||
|
*/
|
||||||
|
export interface AdminGeneralFeedbackReportRow {
|
||||||
|
id: number;
|
||||||
|
status?: string;
|
||||||
|
[key: string]: unknown;
|
||||||
|
images?: FeedbackReportImage[];
|
||||||
|
}
|
||||||
export const batchDeleteAdminChatLogs = (ids: number[]) =>
|
export const batchDeleteAdminChatLogs = (ids: number[]) =>
|
||||||
requestJson<{ deleted_count: number }>('/api/admin/database/chat_logs/batch-delete', {
|
requestJson<{ deleted_count: number }>('/api/admin/database/chat_logs/batch-delete', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
|
|||||||
@@ -4,6 +4,7 @@
|
|||||||
* 依赖:useReportsAdmin、AdminListPage、AdminListTabs、element-plus、@element-plus/icons-vue。
|
* 依赖:useReportsAdmin、AdminListPage、AdminListTabs、element-plus、@element-plus/icons-vue。
|
||||||
* 逻辑:路由 /admin/reports/:table?。看板块用 ElCard;有表格的页签用 AdminListPage。
|
* 逻辑:路由 /admin/reports/:table?。看板块用 ElCard;有表格的页签用 AdminListPage。
|
||||||
* 反馈页签用 AdminListTabs。筛选和分页沿用 composable 里的原状态。删除聊天日志用 Element 确认框。
|
* 反馈页签用 AdminListTabs。筛选和分页沿用 composable 里的原状态。删除聊天日志用 Element 确认框。
|
||||||
|
* 意见反馈附图列为懒加载缩略图(composable 内 blob objectURL 缓存),页面附 lightbox 大图预览。
|
||||||
*/
|
*/
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { computed, onMounted } from 'vue';
|
import { computed, onMounted } from 'vue';
|
||||||
@@ -49,6 +50,7 @@ import AdminListPage from '@/features/admin/components/AdminListPage.vue';
|
|||||||
import AdminListTabs from '@/features/admin/components/AdminListTabs.vue';
|
import AdminListTabs from '@/features/admin/components/AdminListTabs.vue';
|
||||||
import type { ApplicationReportItem, ApplicationSortKey, ApplicationUsageFilter } from '@/features/admin/types/report.types';
|
import type { ApplicationReportItem, ApplicationSortKey, ApplicationUsageFilter } from '@/features/admin/types/report.types';
|
||||||
import { formatLocalDateTime } from '@/shared/utils/dateTime';
|
import { formatLocalDateTime } from '@/shared/utils/dateTime';
|
||||||
|
import type { FeedbackReportImage } from '../../api/admin.api';
|
||||||
import { useReportsAdmin } from './composables/useReportsAdmin';
|
import { useReportsAdmin } from './composables/useReportsAdmin';
|
||||||
|
|
||||||
const vLoading = ElLoading.directive;
|
const vLoading = ElLoading.directive;
|
||||||
@@ -181,6 +183,12 @@ const {
|
|||||||
generalFeedbackTotal,
|
generalFeedbackTotal,
|
||||||
feedbackSummary,
|
feedbackSummary,
|
||||||
closeFeedback,
|
closeFeedback,
|
||||||
|
feedbackImagePreview,
|
||||||
|
feedbackImageUrl,
|
||||||
|
loadFeedbackImage,
|
||||||
|
openFeedbackImagePreview,
|
||||||
|
closeFeedbackImagePreview,
|
||||||
|
stepFeedbackImagePreview,
|
||||||
feedbackTypeOptions,
|
feedbackTypeOptions,
|
||||||
feedbackModuleOptions,
|
feedbackModuleOptions,
|
||||||
feedbackSourceOptions,
|
feedbackSourceOptions,
|
||||||
@@ -231,6 +239,26 @@ const {
|
|||||||
batchDeleteChatLogs,
|
batchDeleteChatLogs,
|
||||||
} = useReportsAdmin();
|
} = useReportsAdmin();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 当前大图预览指向的附图元数据(下标越界时钳制,防翻页竞态渲染 undefined)。
|
||||||
|
*/
|
||||||
|
const currentPreviewImage = computed(() => {
|
||||||
|
const preview = feedbackImagePreview.value;
|
||||||
|
if (!preview || preview.images.length === 0) return null;
|
||||||
|
const safeIndex = Math.min(Math.max(0, preview.index), preview.images.length - 1);
|
||||||
|
return preview.images[safeIndex] || null;
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 当前大图的 blob objectURL(未加载完成返回空串,lightbox 由 v-if 隐藏 <img>)。
|
||||||
|
*/
|
||||||
|
const currentPreviewUrl = computed(() => {
|
||||||
|
const preview = feedbackImagePreview.value;
|
||||||
|
const image = currentPreviewImage.value;
|
||||||
|
if (!preview || !image) return '';
|
||||||
|
return feedbackImageUrl(preview.feedbackId, image.image_id) || '';
|
||||||
|
});
|
||||||
|
|
||||||
/** 应用运营可点击排序的列 */
|
/** 应用运营可点击排序的列 */
|
||||||
const applicationSortableKeys: ApplicationSortKey[] = [
|
const applicationSortableKeys: ApplicationSortKey[] = [
|
||||||
'name',
|
'name',
|
||||||
@@ -672,6 +700,16 @@ function isGeneralFeedbackContent(columnKey: string): boolean {
|
|||||||
return isMergedFeedbackTable.value && feedbackTab.value === 'general' && columnKey === 'content';
|
return isMergedFeedbackTable.value && feedbackTab.value === 'general' && columnKey === 'content';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 意见反馈行的附图元数据。
|
||||||
|
* @param row - 当前行
|
||||||
|
* @returns 附图元数据数组;无图或字段缺失时为空数组
|
||||||
|
*/
|
||||||
|
function rowFeedbackImages(row: ReportTableRow): FeedbackReportImage[] {
|
||||||
|
const images = (row as { images?: FeedbackReportImage[] }).images;
|
||||||
|
return Array.isArray(images) ? images : [];
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 意见反馈操作列。
|
* 意见反馈操作列。
|
||||||
* @param columnKey - 列字段
|
* @param columnKey - 列字段
|
||||||
@@ -1779,6 +1817,25 @@ onMounted(() => {
|
|||||||
</span>
|
</span>
|
||||||
</template>
|
</template>
|
||||||
</ElPopover>
|
</ElPopover>
|
||||||
|
<!-- 意见反馈附图列:懒加载缩略图(<img> 无法带鉴权头,blob URL 由 composable 缓存),点击放大;无图显示 - -->
|
||||||
|
<template v-else-if="isMergedFeedbackTable && columnKey === 'images'">
|
||||||
|
<div class="flex items-center gap-1">
|
||||||
|
<template v-if="rowFeedbackImages(row as ReportTableRow).length">
|
||||||
|
<img
|
||||||
|
v-for="(img, i) in rowFeedbackImages(row as ReportTableRow)"
|
||||||
|
:key="img.image_id"
|
||||||
|
:src="feedbackImageUrl(Number((row as ReportTableRow).id), img.image_id) || ''"
|
||||||
|
:alt="img.original_filename"
|
||||||
|
loading="lazy"
|
||||||
|
class="h-10 w-10 cursor-pointer rounded border border-default object-cover"
|
||||||
|
@load="loadFeedbackImage(Number((row as ReportTableRow).id), img.image_id)"
|
||||||
|
@error="loadFeedbackImage(Number((row as ReportTableRow).id), img.image_id)"
|
||||||
|
@click.stop="openFeedbackImagePreview(row as ReportTableRow, Number(i))"
|
||||||
|
/>
|
||||||
|
</template>
|
||||||
|
<span v-else class="report-muted">-</span>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
<template v-else-if="isMergedFeedbackTable && columnKey === 'chat_log_id'">
|
<template v-else-if="isMergedFeedbackTable && columnKey === 'chat_log_id'">
|
||||||
<ElButton
|
<ElButton
|
||||||
v-if="getFeedbackChatLogCell(row as ReportTableRow).type === 'link'"
|
v-if="getFeedbackChatLogCell(row as ReportTableRow).type === 'link'"
|
||||||
@@ -1895,6 +1952,35 @@ onMounted(() => {
|
|||||||
<ElButton @click="closeChatLogDetail">{{ t('admin.report.chatLog.close') }}</ElButton>
|
<ElButton @click="closeChatLogDetail">{{ t('admin.report.chatLog.close') }}</ElButton>
|
||||||
</template>
|
</template>
|
||||||
</ElDialog>
|
</ElDialog>
|
||||||
|
<!-- 意见反馈附图大图预览:深色遮罩 + 前后翻页(blob URL 由 composable 缓存) -->
|
||||||
|
<div
|
||||||
|
v-if="feedbackImagePreview"
|
||||||
|
class="fixed inset-0 z-50 flex items-center justify-center p-4"
|
||||||
|
>
|
||||||
|
<div class="absolute inset-0 bg-black/70" @click="closeFeedbackImagePreview"></div>
|
||||||
|
<div class="relative flex max-h-[90vh] max-w-[90vw] flex-col items-center gap-3">
|
||||||
|
<div class="flex items-center gap-4">
|
||||||
|
<button type="button" class="btn-icon-ds text-white" @click.stop="stepFeedbackImagePreview(-1)">‹</button>
|
||||||
|
<img
|
||||||
|
v-if="currentPreviewUrl"
|
||||||
|
:src="currentPreviewUrl"
|
||||||
|
:alt="currentPreviewImage?.original_filename"
|
||||||
|
class="max-h-[80vh] max-w-[80vw] rounded object-contain"
|
||||||
|
/>
|
||||||
|
<button type="button" class="btn-icon-ds text-white" @click.stop="stepFeedbackImagePreview(1)">›</button>
|
||||||
|
</div>
|
||||||
|
<div class="flex items-center gap-3 text-sm text-white/80">
|
||||||
|
<span>{{ feedbackImagePreview.index + 1 }} / {{ feedbackImagePreview.images.length }}</span>
|
||||||
|
<span>{{ currentPreviewImage?.original_filename }}</span>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="btn-icon-ds"
|
||||||
|
:title="t('admin.report.feedback.closePreview')"
|
||||||
|
@click="closeFeedbackImagePreview"
|
||||||
|
>✕</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
|
|||||||
@@ -5,9 +5,10 @@
|
|||||||
* 逻辑:ReportsPage 调用本 composable;使用分析按用户服务端分页、按应用前端分页,页码状态交给页面的 ElPagination;
|
* 逻辑:ReportsPage 调用本 composable;使用分析按用户服务端分页、按应用前端分页,页码状态交给页面的 ElPagination;
|
||||||
* 低使用应用优先消费后端 low_agents(含零使用启用应用),与应用运营口径对齐;
|
* 低使用应用优先消费后端 low_agents(含零使用启用应用),与应用运营口径对齐;
|
||||||
* 统计范围统一为开始/结束日期(默认近 30 天),经 start_date/end_date 传给后端,聊天日志走 created_from/created_to;
|
* 统计范围统一为开始/结束日期(默认近 30 天),经 start_date/end_date 传给后端,聊天日志走 created_from/created_to;
|
||||||
* 趋势 by_day 前端按日期升序兜底;问题分析优先问题表前端分页;非表页切换时清空通用表状态防幽灵分页。
|
* 趋势 by_day 前端按日期升序兜底;问题分析优先问题表前端分页;非表页切换时清空通用表状态防幽灵分页;
|
||||||
|
* 意见反馈附图经 requestBlob 代理接口懒加载 objectURL(缓存键 feedbackId:imageId),支持行内缩略图与大图循环预览。
|
||||||
*/
|
*/
|
||||||
import { computed, ref, watch } from 'vue';
|
import { computed, reactive, ref, watch } from 'vue';
|
||||||
import { useI18n } from 'vue-i18n';
|
import { useI18n } from 'vue-i18n';
|
||||||
import { useRoute, useRouter } from 'vue-router';
|
import { useRoute, useRouter } from 'vue-router';
|
||||||
import { ElMessageBox } from 'element-plus';
|
import { ElMessageBox } from 'element-plus';
|
||||||
@@ -25,6 +26,7 @@ import {
|
|||||||
getAdminUsageReport,
|
getAdminUsageReport,
|
||||||
listAdminAgents,
|
listAdminAgents,
|
||||||
} from '@/features/admin/api/admin.api';
|
} from '@/features/admin/api/admin.api';
|
||||||
|
import { requestBlob } from '@/shared/api/client';
|
||||||
import { loadReportLayoutPref, saveReportLayoutPref } from '@/shared/composables/useReportLayoutStorage';
|
import { loadReportLayoutPref, saveReportLayoutPref } from '@/shared/composables/useReportLayoutStorage';
|
||||||
import { buildOffsetPageButtons } from '@/shared/composables/useOffsetPagination';
|
import { buildOffsetPageButtons } from '@/shared/composables/useOffsetPagination';
|
||||||
import { useMessage } from '@/shared/composables/useMessage';
|
import { useMessage } from '@/shared/composables/useMessage';
|
||||||
@@ -44,6 +46,7 @@ import type {
|
|||||||
UsageReport,
|
UsageReport,
|
||||||
} from '@/features/admin/types/report.types';
|
} from '@/features/admin/types/report.types';
|
||||||
import type { AdminReportTableId } from '@/features/admin/types/admin.types';
|
import type { AdminReportTableId } from '@/features/admin/types/admin.types';
|
||||||
|
import type { FeedbackReportImage } from '@/features/admin/api/admin.api';
|
||||||
|
|
||||||
/** 聊天日志报表固定展示列(顺序与产品约定一致;id 仅用于批量删除) */
|
/** 聊天日志报表固定展示列(顺序与产品约定一致;id 仅用于批量删除) */
|
||||||
const CHAT_LOGS_REPORT_KEYS = [
|
const CHAT_LOGS_REPORT_KEYS = [
|
||||||
@@ -65,7 +68,8 @@ const CHAT_LOG_RISK_STATUS_OPTIONS = ['attention', 'review', 'responded'] as con
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* 报表列默认宽度:聊天日志前三列与 Token 收窄,提问/回答留宽,风险列居中紧凑;
|
* 报表列默认宽度:聊天日志前三列与 Token 收窄,提问/回答留宽,风险列居中紧凑;
|
||||||
* 意见反馈操作列保留按钮所需空间,防止中文文案按单字断行拉高整行。
|
* 意见反馈操作列保留按钮所需空间,防止中文文案按单字断行拉高整行;
|
||||||
|
* 意见反馈附图列按 3-4 张 40px 缩略图横排估宽。
|
||||||
* @param key - 列字段名
|
* @param key - 列字段名
|
||||||
* @returns 像素宽度
|
* @returns 像素宽度
|
||||||
*/
|
*/
|
||||||
@@ -98,6 +102,8 @@ const defaultChatLogsColumnWidth = (key: string): number => {
|
|||||||
return 240;
|
return 240;
|
||||||
case 'actions':
|
case 'actions':
|
||||||
return 112;
|
return 112;
|
||||||
|
case 'images':
|
||||||
|
return 176;
|
||||||
default:
|
default:
|
||||||
return 160;
|
return 160;
|
||||||
}
|
}
|
||||||
@@ -381,6 +387,87 @@ export function useReportsAdmin() {
|
|||||||
chatLogDetailRow.value = null;
|
chatLogDetailRow.value = null;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// ===== 意见反馈附图:blob 懒加载缓存 + 大图循环预览 =====
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 附图 objectURL 缓存(reactive Map,模板读取其键值建立响应依赖)。
|
||||||
|
* 键:`${feedbackId}:${imageId}`;值:blob objectURL,''=加载失败/加载中占位(<img> 空 src,不重试)。
|
||||||
|
* 回收语义:缓存随页面会话存续、objectURL 刻意不 revoke——缩略图与大图共享同一 URL,
|
||||||
|
* 提前回收会让已渲染的 <img> 变裂图;页面刷新时由浏览器统一回收。
|
||||||
|
*/
|
||||||
|
const feedbackImageObjectUrls = reactive(new Map<string, string>());
|
||||||
|
|
||||||
|
/** 当前大图预览状态(null=未打开):feedbackId 拼接 raw 接口,images/index 支持在单条反馈内循环翻页 */
|
||||||
|
const feedbackImagePreview = ref<{ feedbackId: number; images: FeedbackReportImage[]; index: number } | null>(null);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 读取附图 objectURL(【AI 触发时机】模板 :src 绑定按此取值,无需手动刷新)。
|
||||||
|
* @param feedbackId - 反馈行 id(禁止传 undefined/0)
|
||||||
|
* @param imageId - 附图 id(禁止传 undefined/0)
|
||||||
|
* @returns blob objectURL;未加载过返回 null;加载失败返回 ''(<img> 显示空占位)
|
||||||
|
*/
|
||||||
|
const feedbackImageUrl = (feedbackId: number, imageId: number): string | null => {
|
||||||
|
const url = feedbackImageObjectUrls.get(`${feedbackId}:${imageId}`);
|
||||||
|
return url === undefined ? null : url;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 懒加载单张附图为 blob objectURL(【AI 触发时机】缩略图 @load/@error 或打开/翻页大图时调用)。
|
||||||
|
* 核心逻辑:<img> 无法自带鉴权头,必须经 requestBlob 代理接口取流再 createObjectURL。
|
||||||
|
* [STEP 1] 缓存已有键(含 objectURL 与 ''占位)直接返回,避免 @load/@error 反复触发重复请求;
|
||||||
|
* [STEP 2] 同步写入 ''占位实现并发去重,随后异步请求;成功覆盖为 objectURL(响应式触发单元格重渲),
|
||||||
|
* 失败静默保持 ''占位——空 src 不会再触发 error 事件,天然防止无限重试。
|
||||||
|
* @param feedbackId - 反馈行 id(禁止传 undefined/0)
|
||||||
|
* @param imageId - 附图 id(禁止传 undefined/0)
|
||||||
|
*/
|
||||||
|
const loadFeedbackImage = async (feedbackId: number, imageId: number): Promise<void> => {
|
||||||
|
if (!Number.isFinite(feedbackId) || !Number.isFinite(imageId) || feedbackId <= 0 || imageId <= 0) return;
|
||||||
|
const key = `${feedbackId}:${imageId}`;
|
||||||
|
if (feedbackImageObjectUrls.has(key)) return;
|
||||||
|
feedbackImageObjectUrls.set(key, '');
|
||||||
|
try {
|
||||||
|
const { blob } = await requestBlob(
|
||||||
|
`/api/admin/reports/general-feedbacks/${feedbackId}/images/${imageId}/raw`,
|
||||||
|
);
|
||||||
|
feedbackImageObjectUrls.set(key, URL.createObjectURL(blob));
|
||||||
|
} catch {
|
||||||
|
// 拉取失败保持 ''占位:单元格显示空缩略图即可,不打断报表浏览
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 打开附图大图预览(【AI 触发时机】点击行内缩略图时调用)。
|
||||||
|
* @param row - 意见反馈行(须含 id 与 images 元数据;无图行直接忽略)
|
||||||
|
* @param index - 预览起始附图下标(越界时钳制到最后一张)
|
||||||
|
*/
|
||||||
|
const openFeedbackImagePreview = (row: any, index: number): void => {
|
||||||
|
const feedbackId = Number(row?.id);
|
||||||
|
const images = Array.isArray(row?.images) ? row.images : [];
|
||||||
|
if (!Number.isFinite(feedbackId) || feedbackId <= 0 || images.length === 0) return;
|
||||||
|
const safeIndex = Math.min(Math.max(0, Number(index) || 0), images.length - 1);
|
||||||
|
feedbackImagePreview.value = { feedbackId, images, index: safeIndex };
|
||||||
|
void loadFeedbackImage(feedbackId, images[safeIndex].image_id);
|
||||||
|
};
|
||||||
|
|
||||||
|
/** 关闭附图大图预览(objectURL 缓存保留,行内缩略图复用同一 URL) */
|
||||||
|
const closeFeedbackImagePreview = (): void => {
|
||||||
|
feedbackImagePreview.value = null;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 大图预览翻页(【AI 触发时机】lightbox 左右箭头按钮调用)。
|
||||||
|
* 核心逻辑:index 仅在当前反馈的 images 内 +1/-1 取模循环,不跨反馈串联。
|
||||||
|
* @param delta - 翻页步长(1=下一张,-1=上一张;其他值按取模处理)
|
||||||
|
*/
|
||||||
|
const stepFeedbackImagePreview = (delta: number): void => {
|
||||||
|
const preview = feedbackImagePreview.value;
|
||||||
|
if (!preview || preview.images.length === 0) return;
|
||||||
|
const len = preview.images.length;
|
||||||
|
preview.index = (((preview.index + delta) % len) + len) % len;
|
||||||
|
const next = preview.images[preview.index];
|
||||||
|
if (next) void loadFeedbackImage(preview.feedbackId, next.image_id);
|
||||||
|
};
|
||||||
|
|
||||||
/** 风险状态 → 本地化标签 */
|
/** 风险状态 → 本地化标签 */
|
||||||
const getChatLogRiskStatusLabel = (status: string): string => {
|
const getChatLogRiskStatusLabel = (status: string): string => {
|
||||||
const key = `admin.report.chatLog.risk.${status}`;
|
const key = `admin.report.chatLog.risk.${status}`;
|
||||||
@@ -1048,6 +1135,7 @@ const visibleReportKeys = computed(() => {
|
|||||||
'feedback_module',
|
'feedback_module',
|
||||||
'feedback_type',
|
'feedback_type',
|
||||||
'content',
|
'content',
|
||||||
|
'images',
|
||||||
'username',
|
'username',
|
||||||
'real_name',
|
'real_name',
|
||||||
'department',
|
'department',
|
||||||
@@ -1122,6 +1210,7 @@ const feedbackReportI18nMap: Record<string, FeedbackReportI18nPack> = {
|
|||||||
/** 意见反馈 Tab 专用列名(覆盖通用列名,主要在关联跳转列) */
|
/** 意见反馈 Tab 专用列名(覆盖通用列名,主要在关联跳转列) */
|
||||||
generalColumns: {
|
generalColumns: {
|
||||||
chat_log_id: 'Linked Chat',
|
chat_log_id: 'Linked Chat',
|
||||||
|
images: 'Images',
|
||||||
},
|
},
|
||||||
/** 回答评价 Tab 列名:更易读、贴合评价语境 */
|
/** 回答评价 Tab 列名:更易读、贴合评价语境 */
|
||||||
ratingColumns: {
|
ratingColumns: {
|
||||||
@@ -1158,6 +1247,7 @@ const feedbackReportI18nMap: Record<string, FeedbackReportI18nPack> = {
|
|||||||
},
|
},
|
||||||
generalColumns: {
|
generalColumns: {
|
||||||
chat_log_id: '\u5173\u8054\u804a\u5929',
|
chat_log_id: '\u5173\u8054\u804a\u5929',
|
||||||
|
images: '\u9644\u56fe',
|
||||||
},
|
},
|
||||||
ratingColumns: {
|
ratingColumns: {
|
||||||
chat_log_id: '\u5173\u8054\u804a\u5929',
|
chat_log_id: '\u5173\u8054\u804a\u5929',
|
||||||
@@ -1193,6 +1283,7 @@ const feedbackReportI18nMap: Record<string, FeedbackReportI18nPack> = {
|
|||||||
},
|
},
|
||||||
generalColumns: {
|
generalColumns: {
|
||||||
chat_log_id: '\u95dc\u806f\u804a\u5929',
|
chat_log_id: '\u95dc\u806f\u804a\u5929',
|
||||||
|
images: '\u9644\u5716',
|
||||||
},
|
},
|
||||||
ratingColumns: {
|
ratingColumns: {
|
||||||
chat_log_id: '\u95dc\u806f\u804a\u5929',
|
chat_log_id: '\u95dc\u806f\u804a\u5929',
|
||||||
@@ -1228,6 +1319,7 @@ const feedbackReportI18nMap: Record<string, FeedbackReportI18nPack> = {
|
|||||||
},
|
},
|
||||||
generalColumns: {
|
generalColumns: {
|
||||||
chat_log_id: '\u0e41\u0e0a\u0e17\u0e17\u0e35\u0e48\u0e40\u0e0a\u0e37\u0e48\u0e2d\u0e21\u0e42\u0e22\u0e07',
|
chat_log_id: '\u0e41\u0e0a\u0e17\u0e17\u0e35\u0e48\u0e40\u0e0a\u0e37\u0e48\u0e2d\u0e21\u0e42\u0e22\u0e07',
|
||||||
|
images: '\u0e23\u0e39\u0e1b\u0e20\u0e32\u0e1e',
|
||||||
},
|
},
|
||||||
ratingColumns: {
|
ratingColumns: {
|
||||||
chat_log_id: '\u0e41\u0e0a\u0e17\u0e17\u0e35\u0e48\u0e40\u0e0a\u0e37\u0e48\u0e2d\u0e21\u0e42\u0e22\u0e07',
|
chat_log_id: '\u0e41\u0e0a\u0e17\u0e17\u0e35\u0e48\u0e40\u0e0a\u0e37\u0e48\u0e2d\u0e21\u0e42\u0e22\u0e07',
|
||||||
@@ -1351,6 +1443,11 @@ const getReportCellValue = (row: any, key: string) => {
|
|||||||
return getTranslatedFeedbackValue('pages', value);
|
return getTranslatedFeedbackValue('pages', value);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (key === 'images') {
|
||||||
|
// 附图列为对象数组:单元格由专用分支渲染缩略图;此处返回张数,供表头排序与 Excel 导出,避免出现 [object Object]
|
||||||
|
return Array.isArray(value) ? value.length : 0;
|
||||||
|
}
|
||||||
|
|
||||||
// format datetime fields in report table
|
// format datetime fields in report table
|
||||||
if (typeof value === 'string' && (key.endsWith('_at') || key === 'created_at' || key === 'updated_at')) {
|
if (typeof value === 'string' && (key.endsWith('_at') || key === 'created_at' || key === 'updated_at')) {
|
||||||
return formatReportDateTime(value);
|
return formatReportDateTime(value);
|
||||||
@@ -1868,6 +1965,12 @@ watch([reportPageSize, issueQuestionTotal], () => {
|
|||||||
feedbackSummary,
|
feedbackSummary,
|
||||||
expandedFeedbackId,
|
expandedFeedbackId,
|
||||||
closeFeedback,
|
closeFeedback,
|
||||||
|
feedbackImagePreview,
|
||||||
|
feedbackImageUrl,
|
||||||
|
loadFeedbackImage,
|
||||||
|
openFeedbackImagePreview,
|
||||||
|
closeFeedbackImagePreview,
|
||||||
|
stepFeedbackImagePreview,
|
||||||
feedbackTypeOptions,
|
feedbackTypeOptions,
|
||||||
feedbackModuleOptions,
|
feedbackModuleOptions,
|
||||||
feedbackSourceOptions,
|
feedbackSourceOptions,
|
||||||
|
|||||||
@@ -52,7 +52,6 @@ async function handleQueryPreviewAssetImage(assetId: string, assetName: string)
|
|||||||
/>
|
/>
|
||||||
<GeneralFeedbackDialog
|
<GeneralFeedbackDialog
|
||||||
v-model="page.showGeneralFeedbackDialog"
|
v-model="page.showGeneralFeedbackDialog"
|
||||||
:auth-headers="getAuthHeaders()"
|
|
||||||
source-page="chat"
|
source-page="chat"
|
||||||
:chat-log-id="page.currentGeneralFeedbackChatLogId"
|
:chat-log-id="page.currentGeneralFeedbackChatLogId"
|
||||||
@submitted="onFeedbackSubmitted"
|
@submitted="onFeedbackSubmitted"
|
||||||
|
|||||||
@@ -13,7 +13,6 @@ import 'element-plus/theme-chalk/dark/css-vars.css';
|
|||||||
import '@/shared/styles/element-theme.css';
|
import '@/shared/styles/element-theme.css';
|
||||||
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
|
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
|
||||||
import GeneralFeedbackDialog from '@/shared/components/GeneralFeedbackDialog.vue';
|
import GeneralFeedbackDialog from '@/shared/components/GeneralFeedbackDialog.vue';
|
||||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
|
||||||
import { WORKSPACE_KEY } from '../composables/workspace.context';
|
import { WORKSPACE_KEY } from '../composables/workspace.context';
|
||||||
|
|
||||||
const ws = inject(WORKSPACE_KEY)! as any;
|
const ws = inject(WORKSPACE_KEY)! as any;
|
||||||
@@ -106,7 +105,6 @@ function submitPassword(): void {
|
|||||||
/>
|
/>
|
||||||
<GeneralFeedbackDialog
|
<GeneralFeedbackDialog
|
||||||
v-model="ws.showGeneralFeedbackDialog"
|
v-model="ws.showGeneralFeedbackDialog"
|
||||||
:auth-headers="getAuthHeaders()"
|
|
||||||
source-page="workspace"
|
source-page="workspace"
|
||||||
@submitted="ws.msg.success('反馈提交成功')"
|
@submitted="ws.msg.success('反馈提交成功')"
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -2369,6 +2369,7 @@
|
|||||||
"markClosed": "Mark closed",
|
"markClosed": "Mark closed",
|
||||||
"closed": "Closed",
|
"closed": "Closed",
|
||||||
"closedOk": "Marked as closed",
|
"closedOk": "Marked as closed",
|
||||||
|
"closePreview": "Close preview",
|
||||||
"summary": {
|
"summary": {
|
||||||
"pending": "Pending",
|
"pending": "Pending",
|
||||||
"pendingHint": "Feedback to follow up",
|
"pendingHint": "Feedback to follow up",
|
||||||
|
|||||||
@@ -297,6 +297,9 @@
|
|||||||
"FILE_ASSET_FORBIDDEN": "You do not have access to this file asset.",
|
"FILE_ASSET_FORBIDDEN": "You do not have access to this file asset.",
|
||||||
"FILE_ASSET_UPLOAD_FAILED": "File upload failed. Please try again later.",
|
"FILE_ASSET_UPLOAD_FAILED": "File upload failed. Please try again later.",
|
||||||
"FILE_ASSET_INVALID_TYPE": "Unsupported file type.",
|
"FILE_ASSET_INVALID_TYPE": "Unsupported file type.",
|
||||||
|
"FEEDBACK_IMAGE_INVALID": "The feedback image is invalid or already in use.",
|
||||||
|
"FEEDBACK_IMAGE_TOO_MANY": "Too many feedback images.",
|
||||||
|
"FEEDBACK_IMAGE_NOT_FOUND": "Feedback image not found.",
|
||||||
"FILE_ASSET_SIZE_EXCEEDED": "File size exceeds the limit.",
|
"FILE_ASSET_SIZE_EXCEEDED": "File size exceeds the limit.",
|
||||||
"FILE_ASSET_EXPIRED": "File asset has expired.",
|
"FILE_ASSET_EXPIRED": "File asset has expired.",
|
||||||
"FILE_ASSET_ALREADY_REFERENCED": "File asset is already referenced and cannot be deleted.",
|
"FILE_ASSET_ALREADY_REFERENCED": "File asset is already referenced and cannot be deleted.",
|
||||||
|
|||||||
@@ -26,5 +26,14 @@
|
|||||||
},
|
},
|
||||||
"cancel": "Cancel",
|
"cancel": "Cancel",
|
||||||
"submitting": "Submitting...",
|
"submitting": "Submitting...",
|
||||||
"submit": "Submit"
|
"submit": "Submit",
|
||||||
|
"upload": {
|
||||||
|
"addImage": "Add images",
|
||||||
|
"pasteHint": "Paste a screenshot (Ctrl+V) or click to add, up to 5",
|
||||||
|
"maxCount": "Up to {count} images",
|
||||||
|
"maxSize": "Each image must be within {size}MB",
|
||||||
|
"invalidType": "Only png / jpg / jpeg / webp images are supported",
|
||||||
|
"uploadFailed": "Image upload failed, please retry",
|
||||||
|
"remove": "Remove image"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -2351,6 +2351,7 @@
|
|||||||
"markClosed": "ทำเครื่องหมายว่าปิดแล้ว",
|
"markClosed": "ทำเครื่องหมายว่าปิดแล้ว",
|
||||||
"closed": "ปิดแล้ว",
|
"closed": "ปิดแล้ว",
|
||||||
"closedOk": "ทำเครื่องหมายว่าปิดแล้ว",
|
"closedOk": "ทำเครื่องหมายว่าปิดแล้ว",
|
||||||
|
"closePreview": "ปิดตัวอย่าง",
|
||||||
"summary": {
|
"summary": {
|
||||||
"pending": "รอดำเนินการ",
|
"pending": "รอดำเนินการ",
|
||||||
"pendingHint": "ข้อเสนอแนะรอติดตาม",
|
"pendingHint": "ข้อเสนอแนะรอติดตาม",
|
||||||
|
|||||||
@@ -297,6 +297,9 @@
|
|||||||
"FILE_ASSET_FORBIDDEN": "คุณไม่มีสิทธิ์เข้าถึงไฟล์นี้",
|
"FILE_ASSET_FORBIDDEN": "คุณไม่มีสิทธิ์เข้าถึงไฟล์นี้",
|
||||||
"FILE_ASSET_UPLOAD_FAILED": "อัปโหลดไฟล์ล้มเหลว โปรดลองใหม่ภายหลัง",
|
"FILE_ASSET_UPLOAD_FAILED": "อัปโหลดไฟล์ล้มเหลว โปรดลองใหม่ภายหลัง",
|
||||||
"FILE_ASSET_INVALID_TYPE": "ชนิดไฟล์ไม่รองรับ",
|
"FILE_ASSET_INVALID_TYPE": "ชนิดไฟล์ไม่รองรับ",
|
||||||
|
"FEEDBACK_IMAGE_INVALID": "รูปภาพข้อเสนอแนะไม่ถูกต้องหรือถูกใช้งานแล้ว",
|
||||||
|
"FEEDBACK_IMAGE_TOO_MANY": "จำนวนรูปภาพข้อเสนอแนะเกินกำหนด",
|
||||||
|
"FEEDBACK_IMAGE_NOT_FOUND": "ไม่พบรูปภาพข้อเสนอแนะ",
|
||||||
"FILE_ASSET_SIZE_EXCEEDED": "ขนาดไฟล์เกินขีดจำกัด",
|
"FILE_ASSET_SIZE_EXCEEDED": "ขนาดไฟล์เกินขีดจำกัด",
|
||||||
"FILE_ASSET_EXPIRED": "ไฟล์หมดอายุแล้ว",
|
"FILE_ASSET_EXPIRED": "ไฟล์หมดอายุแล้ว",
|
||||||
"FILE_ASSET_ALREADY_REFERENCED": "ไฟล์ถูกอ้างอิงโดยธุรกิจแล้ว ไม่สามารถลบได้",
|
"FILE_ASSET_ALREADY_REFERENCED": "ไฟล์ถูกอ้างอิงโดยธุรกิจแล้ว ไม่สามารถลบได้",
|
||||||
|
|||||||
@@ -26,5 +26,14 @@
|
|||||||
},
|
},
|
||||||
"cancel": "ยกเลิก",
|
"cancel": "ยกเลิก",
|
||||||
"submitting": "กำลังส่ง...",
|
"submitting": "กำลังส่ง...",
|
||||||
"submit": "ส่ง"
|
"submit": "ส่ง",
|
||||||
|
"upload": {
|
||||||
|
"addImage": "เพิ่มรูปภาพ",
|
||||||
|
"pasteHint": "วางภาพหน้าจอ (Ctrl+V) หรือคลิกเพื่อเพิ่ม สูงสุด 5 รูป",
|
||||||
|
"maxCount": "เพิ่มได้สูงสุด {count} รูป",
|
||||||
|
"maxSize": "รูปภาพเดียวต้องไม่เกิน {size}MB",
|
||||||
|
"invalidType": "รองรับเฉพาะไฟล์ png / jpg / jpeg / webp",
|
||||||
|
"uploadFailed": "อัปโหลดรูปภาพไม่สำเร็จ กรุณาลองอีกครั้ง",
|
||||||
|
"remove": "นำรูปภาพออก"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -2482,6 +2482,7 @@
|
|||||||
"markClosed": "标记已关闭",
|
"markClosed": "标记已关闭",
|
||||||
"closed": "已关闭",
|
"closed": "已关闭",
|
||||||
"closedOk": "已标记关闭",
|
"closedOk": "已标记关闭",
|
||||||
|
"closePreview": "关闭预览",
|
||||||
"summary": {
|
"summary": {
|
||||||
"pending": "待处理",
|
"pending": "待处理",
|
||||||
"pendingHint": "待跟进反馈",
|
"pendingHint": "待跟进反馈",
|
||||||
|
|||||||
@@ -297,6 +297,9 @@
|
|||||||
"FILE_ASSET_FORBIDDEN": "无权访问该文件资产。",
|
"FILE_ASSET_FORBIDDEN": "无权访问该文件资产。",
|
||||||
"FILE_ASSET_UPLOAD_FAILED": "文件上传失败,请稍后重试。",
|
"FILE_ASSET_UPLOAD_FAILED": "文件上传失败,请稍后重试。",
|
||||||
"FILE_ASSET_INVALID_TYPE": "不支持的文件类型。",
|
"FILE_ASSET_INVALID_TYPE": "不支持的文件类型。",
|
||||||
|
"FEEDBACK_IMAGE_INVALID": "反馈图片无效或已被使用。",
|
||||||
|
"FEEDBACK_IMAGE_TOO_MANY": "反馈图片数量超过上限。",
|
||||||
|
"FEEDBACK_IMAGE_NOT_FOUND": "反馈图片不存在。",
|
||||||
"FILE_ASSET_SIZE_EXCEEDED": "文件大小超过限制。",
|
"FILE_ASSET_SIZE_EXCEEDED": "文件大小超过限制。",
|
||||||
"FILE_ASSET_EXPIRED": "文件资产已过期。",
|
"FILE_ASSET_EXPIRED": "文件资产已过期。",
|
||||||
"FILE_ASSET_ALREADY_REFERENCED": "文件已被业务引用,无法删除。",
|
"FILE_ASSET_ALREADY_REFERENCED": "文件已被业务引用,无法删除。",
|
||||||
|
|||||||
@@ -26,5 +26,14 @@
|
|||||||
},
|
},
|
||||||
"cancel": "取消",
|
"cancel": "取消",
|
||||||
"submitting": "提交中...",
|
"submitting": "提交中...",
|
||||||
"submit": "提交"
|
"submit": "提交",
|
||||||
|
"upload": {
|
||||||
|
"addImage": "添加图片",
|
||||||
|
"pasteHint": "支持粘贴截图(Ctrl+V)或点击添加,最多 5 张",
|
||||||
|
"maxCount": "最多添加 {count} 张图片",
|
||||||
|
"maxSize": "单张图片不能超过 {size}MB",
|
||||||
|
"invalidType": "仅支持 png / jpg / jpeg / webp 格式图片",
|
||||||
|
"uploadFailed": "图片上传失败,请重试",
|
||||||
|
"remove": "移除图片"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -2351,6 +2351,7 @@
|
|||||||
"markClosed": "標記已關閉",
|
"markClosed": "標記已關閉",
|
||||||
"closed": "已關閉",
|
"closed": "已關閉",
|
||||||
"closedOk": "已標記關閉",
|
"closedOk": "已標記關閉",
|
||||||
|
"closePreview": "關閉預覽",
|
||||||
"summary": {
|
"summary": {
|
||||||
"pending": "待處理",
|
"pending": "待處理",
|
||||||
"pendingHint": "待跟進反饋",
|
"pendingHint": "待跟進反饋",
|
||||||
|
|||||||
@@ -297,6 +297,9 @@
|
|||||||
"FILE_ASSET_FORBIDDEN": "無權存取該檔案資產。",
|
"FILE_ASSET_FORBIDDEN": "無權存取該檔案資產。",
|
||||||
"FILE_ASSET_UPLOAD_FAILED": "檔案上傳失敗,請稍後重試。",
|
"FILE_ASSET_UPLOAD_FAILED": "檔案上傳失敗,請稍後重試。",
|
||||||
"FILE_ASSET_INVALID_TYPE": "不支援的檔案類型。",
|
"FILE_ASSET_INVALID_TYPE": "不支援的檔案類型。",
|
||||||
|
"FEEDBACK_IMAGE_INVALID": "迴饋圖片無效或已被使用。",
|
||||||
|
"FEEDBACK_IMAGE_TOO_MANY": "迴饋圖片數量超過上限。",
|
||||||
|
"FEEDBACK_IMAGE_NOT_FOUND": "迴饋圖片不存在。",
|
||||||
"FILE_ASSET_SIZE_EXCEEDED": "檔案大小超過限制。",
|
"FILE_ASSET_SIZE_EXCEEDED": "檔案大小超過限制。",
|
||||||
"FILE_ASSET_EXPIRED": "檔案資產已過期。",
|
"FILE_ASSET_EXPIRED": "檔案資產已過期。",
|
||||||
"FILE_ASSET_ALREADY_REFERENCED": "檔案已被業務引用,無法刪除。",
|
"FILE_ASSET_ALREADY_REFERENCED": "檔案已被業務引用,無法刪除。",
|
||||||
|
|||||||
@@ -26,5 +26,14 @@
|
|||||||
},
|
},
|
||||||
"cancel": "取消",
|
"cancel": "取消",
|
||||||
"submitting": "提交中...",
|
"submitting": "提交中...",
|
||||||
"submit": "提交"
|
"submit": "提交",
|
||||||
|
"upload": {
|
||||||
|
"addImage": "添加圖片",
|
||||||
|
"pasteHint": "支援貼上截圖(Ctrl+V)或點擊新增,最多 5 張",
|
||||||
|
"maxCount": "最多新增 {count} 張圖片",
|
||||||
|
"maxSize": "單張圖片不能超過 {size}MB",
|
||||||
|
"invalidType": "僅支援 png / jpg / jpeg / webp 格式圖片",
|
||||||
|
"uploadFailed": "圖片上傳失敗,請重試",
|
||||||
|
"remove": "移除圖片"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,37 +1,57 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
/**
|
/**
|
||||||
* shared/components/GeneralFeedbackDialog.vue
|
* shared/components/GeneralFeedbackDialog.vue
|
||||||
* 用途:工作台和对话里的意见反馈提交弹窗。
|
* 通用意见反馈提交弹窗(Element Plus 版)。
|
||||||
* 依赖:element-plus、/api/user/feedback。
|
* 用途:收集反馈类型/模块/内容,并支持粘贴(Ctrl+V)或点击选择图片;图片先经文件资产接口
|
||||||
* 逻辑:由 FeedbackPage 和 WorkspaceModals 打开。类型、模块和内容仍提交原接口。
|
* 上传换取 asset_no,提交时仅携带上传成功(status==='ready')的 asset_no 列表。
|
||||||
|
* 依赖:element-plus(ElDialog/ElSegmented/ElSelect/ElInput/ElButton/ElMessage)、
|
||||||
|
* shared/api/client.requestJson(自动附鉴权头,失败抛 BusinessError)、
|
||||||
|
* shared/api/file-assets.api.uploadFileAsset、vue-i18n。
|
||||||
|
* 逻辑关系:由 WorkspaceModals(workspace 入口,source_page='workspace')与
|
||||||
|
* ChatViewOverlays(chat 入口,source_page='chat' 且附 chat_log_id)挂载;
|
||||||
|
* 打开/重开与语言切换时重置表单并清理图片预览;提交成功 emit('submitted') 后关闭,
|
||||||
|
* 成功提示由父组件处理。类型/模块提交的是当前语言的展示文案(后端按 ≤32 字符字符串存储)。
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { computed, ref, watch } from 'vue';
|
import { computed, reactive, ref, watch } from 'vue';
|
||||||
import { useI18n } from 'vue-i18n';
|
import { useI18n } from 'vue-i18n';
|
||||||
|
import { Loader2, Plus, X } from 'lucide-vue-next';
|
||||||
import {
|
import {
|
||||||
ElButton,
|
ElButton,
|
||||||
ElDialog,
|
ElDialog,
|
||||||
ElForm,
|
|
||||||
ElFormItem,
|
|
||||||
ElInput,
|
ElInput,
|
||||||
|
ElMessage,
|
||||||
ElOption,
|
ElOption,
|
||||||
ElRadioButton,
|
ElSegmented,
|
||||||
ElRadioGroup,
|
|
||||||
ElSelect,
|
ElSelect,
|
||||||
} from 'element-plus';
|
} from 'element-plus';
|
||||||
import 'element-plus/dist/index.css';
|
import 'element-plus/dist/index.css';
|
||||||
import 'element-plus/theme-chalk/dark/css-vars.css';
|
import 'element-plus/theme-chalk/dark/css-vars.css';
|
||||||
import '@/shared/styles/element-theme.css';
|
import '@/shared/styles/element-theme.css';
|
||||||
|
import { BusinessError, requestJson } from '@/shared/api/client';
|
||||||
|
import { uploadFileAsset } from '@/shared/api/file-assets.api';
|
||||||
|
|
||||||
|
/** 反馈图片数量上限(含上传中与已就绪;超过上限整批拒绝,不静默截取前 N 张)。 */
|
||||||
|
const MAX_FEEDBACK_IMAGES = 5;
|
||||||
|
/** 单张图片大小上限(MB):客户端预校验,避免超大文件先上传再被后端拒绝。 */
|
||||||
|
const MAX_FEEDBACK_IMAGE_SIZE_MB = 10;
|
||||||
|
/** 允许的图片 MIME 类型(与后端校验一致:png/jpg/jpeg/webp)。 */
|
||||||
|
const FEEDBACK_IMAGE_ACCEPT = ['image/png', 'image/jpeg', 'image/webp'];
|
||||||
|
|
||||||
|
interface PendingImage {
|
||||||
|
assetNo: string | null; // 上传成功后的 FA 编号
|
||||||
|
status: 'uploading' | 'ready';
|
||||||
|
previewUrl: string; // URL.createObjectURL(file)
|
||||||
|
filename: string;
|
||||||
|
}
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
modelValue: boolean;
|
modelValue: boolean;
|
||||||
authHeaders?: Record<string, string>;
|
|
||||||
sourcePage?: string;
|
sourcePage?: string;
|
||||||
chatLogId?: number | null;
|
chatLogId?: number | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
const props = withDefaults(defineProps<Props>(), {
|
const props = withDefaults(defineProps<Props>(), {
|
||||||
authHeaders: () => ({}),
|
|
||||||
sourcePage: 'unknown',
|
sourcePage: 'unknown',
|
||||||
chatLogId: null,
|
chatLogId: null,
|
||||||
});
|
});
|
||||||
@@ -43,6 +63,11 @@ const emit = defineEmits<{
|
|||||||
|
|
||||||
const { t, locale } = useI18n({ useScope: 'global' });
|
const { t, locale } = useI18n({ useScope: 'global' });
|
||||||
|
|
||||||
|
const visible = computed({
|
||||||
|
get: () => props.modelValue,
|
||||||
|
set: (v: boolean) => emit('update:modelValue', v),
|
||||||
|
});
|
||||||
|
|
||||||
const typeOptions = computed(() => [
|
const typeOptions = computed(() => [
|
||||||
t('feedback.type.featureSuggestion'),
|
t('feedback.type.featureSuggestion'),
|
||||||
t('feedback.type.issueReport'),
|
t('feedback.type.issueReport'),
|
||||||
@@ -61,8 +86,132 @@ const selectedModule = ref<string>(t('feedback.module.knowledgeBase'));
|
|||||||
const content = ref('');
|
const content = ref('');
|
||||||
const submitting = ref(false);
|
const submitting = ref(false);
|
||||||
const error = ref('');
|
const error = ref('');
|
||||||
|
const images = ref<PendingImage[]>([]);
|
||||||
|
|
||||||
const canSubmit = computed(() => content.value.trim().length > 0 && !submitting.value);
|
const hasUploadingImage = computed(() => images.value.some((i) => i.status === 'uploading'));
|
||||||
|
const canSubmit = computed(() => content.value.trim().length > 0 && !submitting.value && !hasUploadingImage.value);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 批量加入反馈图片(粘贴与文件选择共用入口)。
|
||||||
|
* [AI 触发时机] 无 —— 纯 UI 交互:由 onPaste / onFileChange 调用,AI 不得主动调用。
|
||||||
|
* 核心逻辑:
|
||||||
|
* [STEP 1] 类型过滤:MIME 不在 FEEDBACK_IMAGE_ACCEPT 内的整段提示 invalidType(该批跳过);
|
||||||
|
* [STEP 2] 数量上限:已入队(含上传中)+ 本批有效数量 > MAX_FEEDBACK_IMAGES 时整批拒绝并提示
|
||||||
|
* maxCount,在发起任何上传之前拦截(防图片没传完又超限);
|
||||||
|
* [STEP 3] 逐张校验大小:超过 MAX_FEEDBACK_IMAGE_SIZE_MB 的单张跳过并提示 maxSize;
|
||||||
|
* [STEP 4] 逐张入队 status='uploading' → uploadFileAsset 成功置 ready+assetNo;
|
||||||
|
* 失败则移除该项(同时释放预览 URL)并提示 uploadFailed。
|
||||||
|
* @param files - 待加入的图片 File 列表(调用方保证来自剪贴板或 input.files)
|
||||||
|
* @returns Promise,完成后图片状态已落定(ready 或已移除)
|
||||||
|
*/
|
||||||
|
async function addImages(files: File[]): Promise<void> {
|
||||||
|
if (files.length === 0) return;
|
||||||
|
|
||||||
|
// [STEP 1] 类型过滤:不合法的整段提示一次,避免逐张刷屏
|
||||||
|
const typeValidFiles = files.filter((f) => FEEDBACK_IMAGE_ACCEPT.includes(f.type));
|
||||||
|
if (typeValidFiles.length < files.length) {
|
||||||
|
ElMessage.error(t('feedback.upload.invalidType'));
|
||||||
|
}
|
||||||
|
if (typeValidFiles.length === 0) return;
|
||||||
|
|
||||||
|
// [STEP 2] 数量上限校验必须先于任何上传发起;计数包含上传中与已就绪的图片
|
||||||
|
if (images.value.length + typeValidFiles.length > MAX_FEEDBACK_IMAGES) {
|
||||||
|
ElMessage.error(t('feedback.upload.maxCount', { count: MAX_FEEDBACK_IMAGES }));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const file of typeValidFiles) {
|
||||||
|
// [STEP 3] 单张大小超限:仅跳过该张,不影响同批其他图片
|
||||||
|
if (file.size > MAX_FEEDBACK_IMAGE_SIZE_MB * 1024 * 1024) {
|
||||||
|
ElMessage.error(t('feedback.upload.maxSize', { size: MAX_FEEDBACK_IMAGE_SIZE_MB }));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
// [STEP 4] 入队即占位(缩略图立即可见,uploading 态加遮罩),上传成功后才计入提交。
|
||||||
|
// 必须用 reactive 包装后再入队:uploadFileAsset 的 await 之后对 item 的 assetNo/status 写入
|
||||||
|
// 若发生在原始对象上,不经过数组内代理、不触发依赖更新,hasUploadingImage 的 computed
|
||||||
|
// 缓存永不失效 → 遮罩不消失且 canSubmit 永久为 false(提交按钮永远禁用)。
|
||||||
|
const item = reactive<PendingImage>({
|
||||||
|
assetNo: null,
|
||||||
|
status: 'uploading',
|
||||||
|
previewUrl: URL.createObjectURL(file),
|
||||||
|
filename: file.name,
|
||||||
|
});
|
||||||
|
images.value.push(item);
|
||||||
|
try {
|
||||||
|
const asset = await uploadFileAsset(file);
|
||||||
|
item.assetNo = asset.asset_no;
|
||||||
|
item.status = 'ready';
|
||||||
|
} catch {
|
||||||
|
// 上传失败:从队列移除并释放预览,避免提交时引用不存在的资产
|
||||||
|
const idx = images.value.indexOf(item);
|
||||||
|
if (idx !== -1) {
|
||||||
|
URL.revokeObjectURL(item.previewUrl);
|
||||||
|
images.value.splice(idx, 1);
|
||||||
|
}
|
||||||
|
ElMessage.error(t('feedback.upload.uploadFailed'));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 移除单张反馈图片。
|
||||||
|
* [AI 触发时机] 无 —— 纯 UI 交互:点击缩略图右上角 × 时调用。
|
||||||
|
* 核心逻辑:先 revoke 预览 objectURL(防内存泄漏)再从队列 splice;若该项尚在上传中,
|
||||||
|
* 其上传结果会被丢弃(indexOf 找不到已移除项,不会写回)。
|
||||||
|
* @param index - 待移除项在 images 中的下标
|
||||||
|
*/
|
||||||
|
function removeImage(index: number): void {
|
||||||
|
const item = images.value[index];
|
||||||
|
if (!item) return;
|
||||||
|
URL.revokeObjectURL(item.previewUrl);
|
||||||
|
images.value.splice(index, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 处理弹窗内容区粘贴事件:提取剪贴板中的图片文件加入队列。
|
||||||
|
* [AI 触发时机] 无 —— 纯 UI 交互:仅在图片入队时才 preventDefault;
|
||||||
|
* 纯文本粘贴(无图片文件)不拦截,保证 textarea 文本粘贴行为不受影响。
|
||||||
|
* 核心逻辑:clipboardData.items 中 kind==='file' 且 type 以 'image/' 开头的项同步 getAsFile()
|
||||||
|
* (必须在 await 之前同步取完,剪贴板数据在事件处理后失效);未取到任何文件则直接返回。
|
||||||
|
* @param e - ClipboardEvent
|
||||||
|
*/
|
||||||
|
function onPaste(e: ClipboardEvent): void {
|
||||||
|
const items = e.clipboardData?.items;
|
||||||
|
if (!items) return;
|
||||||
|
const files: File[] = [];
|
||||||
|
for (const item of Array.from(items)) {
|
||||||
|
if (item.kind === 'file' && item.type.startsWith('image/')) {
|
||||||
|
const file = item.getAsFile();
|
||||||
|
if (file) files.push(file);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (files.length === 0) return; // 纯文本粘贴:不拦截,保留默认行为
|
||||||
|
e.preventDefault();
|
||||||
|
void addImages(files);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 处理隐藏 file input 的 change 事件。
|
||||||
|
* [AI 触发时机] 无 —— 纯 UI 交互:点击「添加图片」格子选择文件后触发。
|
||||||
|
* 核心逻辑:取 input.files 交给 addImages,随后立即清空 input.value,
|
||||||
|
* 保证再次选择同一文件也会触发 change。
|
||||||
|
* @param e - input change 事件
|
||||||
|
*/
|
||||||
|
function onFileChange(e: Event): void {
|
||||||
|
const input = e.target as HTMLInputElement;
|
||||||
|
const files = input.files ? Array.from(input.files) : [];
|
||||||
|
void addImages(files);
|
||||||
|
input.value = '';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 清理全部待提交图片:revoke 所有预览 objectURL 并清空队列(防弹窗反复开关导致内存泄漏)。
|
||||||
|
* [AI 触发时机] 无 —— 内部生命周期函数:由 resetForm(打开/语言切换)与弹窗关闭 watch 调用。
|
||||||
|
*/
|
||||||
|
function cleanupImages(): void {
|
||||||
|
images.value.forEach((item) => URL.revokeObjectURL(item.previewUrl));
|
||||||
|
images.value = [];
|
||||||
|
}
|
||||||
|
|
||||||
const closeDialog = () => {
|
const closeDialog = () => {
|
||||||
emit('update:modelValue', false);
|
emit('update:modelValue', false);
|
||||||
@@ -74,12 +223,14 @@ const resetForm = () => {
|
|||||||
content.value = '';
|
content.value = '';
|
||||||
error.value = '';
|
error.value = '';
|
||||||
submitting.value = false;
|
submitting.value = false;
|
||||||
|
cleanupImages();
|
||||||
};
|
};
|
||||||
|
|
||||||
watch(
|
watch(
|
||||||
() => props.modelValue,
|
() => props.modelValue,
|
||||||
(visible) => {
|
(visible) => {
|
||||||
if (visible) resetForm();
|
if (visible) resetForm();
|
||||||
|
else cleanupImages();
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -89,6 +240,14 @@ watch(locale, () => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 提交反馈(经统一 HTTP 客户端,自动附鉴权头)。
|
||||||
|
* [AI 触发时机] 无 —— 纯 UI 交互:点击提交按钮时调用。
|
||||||
|
* 核心逻辑:payload 携带 feedback_type / feedback_module(当前语言展示文案)、content、
|
||||||
|
* source_page、image_asset_nos(仅 status==='ready' 的图、按添加顺序;可为空数组,
|
||||||
|
* 后端把缺失与空数组同等对待),chat 入口另附 chat_log_id;BusinessError 的 message
|
||||||
|
* 展示在内联错误行,成功路径 emit('submitted') 后关闭(成功提示由父组件处理)。
|
||||||
|
*/
|
||||||
const submitFeedback = async () => {
|
const submitFeedback = async () => {
|
||||||
if (!canSubmit.value) {
|
if (!canSubmit.value) {
|
||||||
error.value = t('feedback.msg.fillContent');
|
error.value = t('feedback.msg.fillContent');
|
||||||
@@ -104,31 +263,25 @@ const submitFeedback = async () => {
|
|||||||
feedback_module: selectedModule.value,
|
feedback_module: selectedModule.value,
|
||||||
content: content.value.trim(),
|
content: content.value.trim(),
|
||||||
source_page: props.sourcePage,
|
source_page: props.sourcePage,
|
||||||
|
image_asset_nos: images.value
|
||||||
|
.filter((i) => i.status === 'ready')
|
||||||
|
.map((i) => i.assetNo as string),
|
||||||
};
|
};
|
||||||
|
|
||||||
if (props.chatLogId !== null && props.chatLogId !== undefined) {
|
if (props.chatLogId !== null && props.chatLogId !== undefined) {
|
||||||
payload.chat_log_id = props.chatLogId;
|
payload.chat_log_id = props.chatLogId;
|
||||||
}
|
}
|
||||||
|
|
||||||
const res = await fetch('/api/user/feedback', {
|
await requestJson<void>('/api/user/feedback', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: {
|
headers: { 'Content-Type': 'application/json' },
|
||||||
'Content-Type': 'application/json',
|
|
||||||
...props.authHeaders,
|
|
||||||
},
|
|
||||||
body: JSON.stringify(payload),
|
body: JSON.stringify(payload),
|
||||||
});
|
});
|
||||||
|
|
||||||
const data = await res.json().catch(() => ({}));
|
|
||||||
if (!res.ok) {
|
|
||||||
error.value = data?.error || t('feedback.msg.submitFailed');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
emit('submitted');
|
emit('submitted');
|
||||||
closeDialog();
|
closeDialog();
|
||||||
} catch {
|
} catch (e) {
|
||||||
error.value = t('feedback.msg.submitFailed');
|
error.value = e instanceof BusinessError ? e.message : t('feedback.msg.submitFailed');
|
||||||
} finally {
|
} finally {
|
||||||
submitting.value = false;
|
submitting.value = false;
|
||||||
}
|
}
|
||||||
@@ -137,53 +290,105 @@ const submitFeedback = async () => {
|
|||||||
|
|
||||||
<template>
|
<template>
|
||||||
<ElDialog
|
<ElDialog
|
||||||
:model-value="modelValue"
|
v-model="visible"
|
||||||
:title="t('feedback.title')"
|
:title="t('feedback.title')"
|
||||||
width="680px"
|
width="640px"
|
||||||
align-center
|
|
||||||
append-to-body
|
append-to-body
|
||||||
:close-on-click-modal="false"
|
:close-on-click-modal="false"
|
||||||
@update:model-value="emit('update:modelValue', $event)"
|
|
||||||
>
|
>
|
||||||
<ElForm label-position="top">
|
<div class="space-y-5" @paste="onPaste">
|
||||||
<ElFormItem :label="t('feedback.labels.type')">
|
<div class="space-y-1.5">
|
||||||
<ElRadioGroup v-model="selectedType">
|
<div class="text-sm font-medium text-secondary">{{ t('feedback.labels.type') }}</div>
|
||||||
<ElRadioButton v-for="item in typeOptions" :key="item" :value="item">{{ item }}</ElRadioButton>
|
<ElSegmented v-model="selectedType" :options="typeOptions" />
|
||||||
</ElRadioGroup>
|
</div>
|
||||||
</ElFormItem>
|
|
||||||
<ElFormItem :label="t('feedback.labels.module')">
|
<div class="space-y-1.5">
|
||||||
<ElSelect v-model="selectedModule" class="feedback-module">
|
<div class="text-sm font-medium text-secondary">{{ t('feedback.labels.module') }}</div>
|
||||||
|
<ElSelect v-model="selectedModule" class="w-full">
|
||||||
<ElOption v-for="item in moduleOptions" :key="item" :label="item" :value="item" />
|
<ElOption v-for="item in moduleOptions" :key="item" :label="item" :value="item" />
|
||||||
</ElSelect>
|
</ElSelect>
|
||||||
</ElFormItem>
|
</div>
|
||||||
<ElFormItem :label="t('feedback.labels.content')" required>
|
|
||||||
|
<div class="space-y-1.5">
|
||||||
|
<div class="text-sm font-medium text-secondary">
|
||||||
|
{{ t('feedback.labels.content') }}<span class="ml-0.5 text-red-500">*</span>
|
||||||
|
</div>
|
||||||
<ElInput
|
<ElInput
|
||||||
v-model="content"
|
v-model="content"
|
||||||
type="textarea"
|
type="textarea"
|
||||||
:rows="5"
|
:rows="5"
|
||||||
maxlength="2000"
|
:maxlength="2000"
|
||||||
show-word-limit
|
show-word-limit
|
||||||
|
resize="none"
|
||||||
:placeholder="t('feedback.placeholder.content')"
|
:placeholder="t('feedback.placeholder.content')"
|
||||||
/>
|
/>
|
||||||
<div v-if="error" class="feedback-error">{{ error }}</div>
|
|
||||||
</ElFormItem>
|
<div class="mt-1 flex flex-wrap items-center gap-2">
|
||||||
</ElForm>
|
<div
|
||||||
|
v-for="(img, idx) in images"
|
||||||
|
:key="img.previewUrl"
|
||||||
|
class="relative h-12 w-12"
|
||||||
|
>
|
||||||
|
<div class="h-full w-full overflow-hidden rounded-md border border-gray-200 dark:border-gray-600">
|
||||||
|
<img
|
||||||
|
:src="img.previewUrl"
|
||||||
|
:alt="img.filename"
|
||||||
|
class="h-full w-full object-cover"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<!-- uploading 遮罩:提交按钮在此期间禁用(hasUploadingImage) -->
|
||||||
|
<div
|
||||||
|
v-if="img.status === 'uploading'"
|
||||||
|
class="pointer-events-none absolute inset-0 flex items-center justify-center rounded-md bg-black/50"
|
||||||
|
>
|
||||||
|
<Loader2 class="h-4 w-4 animate-spin text-white" />
|
||||||
|
</div>
|
||||||
|
<ElButton
|
||||||
|
size="small"
|
||||||
|
circle
|
||||||
|
:aria-label="t('feedback.upload.remove')"
|
||||||
|
class="absolute -right-2 -top-2"
|
||||||
|
@click="removeImage(idx)"
|
||||||
|
>
|
||||||
|
<X class="h-3 w-3" />
|
||||||
|
</ElButton>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- label 包裹隐藏 file input:点击格子即唤起文件选择,无需手写按钮 -->
|
||||||
|
<label
|
||||||
|
class="flex h-12 cursor-pointer items-center gap-1.5 rounded-md border border-dashed border-gray-300 px-3 text-sm text-muted transition-colors hover:border-brand-400 hover:text-brand-600 dark:border-gray-600 dark:hover:border-brand-500"
|
||||||
|
>
|
||||||
|
<Plus class="h-4 w-4" />
|
||||||
|
<span>{{ t('feedback.upload.addImage') }}</span>
|
||||||
|
<input
|
||||||
|
type="file"
|
||||||
|
class="hidden"
|
||||||
|
multiple
|
||||||
|
accept="image/png,image/jpeg,image/webp"
|
||||||
|
@change="onFileChange"
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<p class="mt-1 text-xs text-muted">{{ t('feedback.upload.pasteHint') }}</p>
|
||||||
|
|
||||||
|
<!-- 内联错误行(字数统计由 ElInput show-word-limit 在输入框内单一呈现) -->
|
||||||
|
<div v-if="error" class="mt-2 text-base text-red-600">{{ error }}</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<template #footer>
|
<template #footer>
|
||||||
<ElButton :disabled="submitting" @click="closeDialog">{{ t('feedback.cancel') }}</ElButton>
|
<ElButton :disabled="submitting" @click="closeDialog">
|
||||||
<ElButton type="primary" :loading="submitting" :disabled="!canSubmit" @click="submitFeedback">
|
{{ t('feedback.cancel') }}
|
||||||
|
</ElButton>
|
||||||
|
<ElButton
|
||||||
|
type="primary"
|
||||||
|
:loading="submitting"
|
||||||
|
:disabled="!canSubmit"
|
||||||
|
@click="submitFeedback"
|
||||||
|
>
|
||||||
{{ submitting ? t('feedback.submitting') : t('feedback.submit') }}
|
{{ submitting ? t('feedback.submitting') : t('feedback.submit') }}
|
||||||
</ElButton>
|
</ElButton>
|
||||||
</template>
|
</template>
|
||||||
</ElDialog>
|
</ElDialog>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<style scoped>
|
|
||||||
.feedback-module {
|
|
||||||
width: 100%;
|
|
||||||
}
|
|
||||||
|
|
||||||
.feedback-error {
|
|
||||||
margin-top: 8px;
|
|
||||||
color: var(--el-color-danger);
|
|
||||||
}
|
|
||||||
</style>
|
|
||||||
Reference in new issue
Block a user