Compare commits

..
Author SHA1 Message Date
HTEWJ\26070045 d4c30b5825 Merge branch 'dev' into picture-feedback 2026-10-29 13:11:59 +08:00
HTEWJ\26070045 836ddea84d Merge branch 'dev' into picture-feedback
# Conflicts:
#	backend/app/models/__init__.py
#	backend/app/services/voucher_check/notification.py
#	docs/features/accounting-voucher-check/demand.md
#	frontend/src/features/admin/modules/reports/ReportsPage.vue
#	frontend/src/shared/components/GeneralFeedbackDialog.vue
2026-10-29 12:42:02 +08:00
HTEWJ\26070045 34ad40778b Merge branch 'dev' into picture-feedback 2026-10-29 11:04:59 +08:00
HTEWJ\26070045 e8ad4cc743 fix(admin): 反馈图片代理接口按扩展名固定 Content-Type 并禁用嗅探 2026-10-27 09:08:10 +08:00
HTEWJ\26070045 37b743d5d3 docs(funclist): 补充意见反馈截图附件功能项 2026-10-27 08:42:33 +08:00
HTEWJ\26070045 ade440d004 feat(admin): 报表意见反馈页签展示附图缩略图与大图预览 2026-10-27 08:28:13 +08:00
HTEWJ\26070045 3f025fbb9b fix(feedback): 修复图片上传后响应式丢失导致提交按钮永久禁用 2026-10-26 19:40:10 +08:00
HTEWJ\26070045 ed18907e95 style(feedback): 移除弹窗重复的字数统计行 2026-10-26 18:32:05 +08:00
HTEWJ\26070045 a91f26f753 feat(feedback): 反馈弹窗整页替换 Element Plus 并支持粘贴与选图上传 2026-10-26 18:22:57 +08:00
HTEWJ\26070045 b64ed9b792 feat(admin): 报表反馈行内附图元数据与图片代理接口 2026-10-26 17:53:15 +08:00
HTEWJ\26070045 6eb4c76beb feat(feedback): 企微反馈通知增加附图数量行 2026-10-26 17:38:00 +08:00
HTEWJ\26070045 29315cab20 feat(feedback): 提交接口支持携带图片资产并校验引用 2026-10-26 17:15:31 +08:00
HTEWJ\26070045 b31e887b2a docs(feedback): 修正附件表模型注释笔误 2026-10-26 16:25:20 +08:00
HTEWJ\26070045 d094d8eb83 feat(feedback): 新增反馈图片关联表与模型 2026-10-26 16:19:18 +08:00
46 changed files with 1939 additions and 417 deletions

No files matched your search

+15 -1
View File
@@ -5,7 +5,9 @@ backend/app/api/admin/reports.py
依赖:admin.blueprint、services/admin/report_service。
逻辑:/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.core.decorators import require_admin
@@ -134,3 +136,15 @@ def issue_analysis():
def close_general_feedback(feedback_id: int):
"""将一条意见反馈标记为已关闭(status='closed')。"""
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
+1 -1
View File
@@ -12,7 +12,7 @@ from flask import Blueprint
chat_bp = Blueprint('chat', __name__)
# 子模块导入时在同一 Blueprint 上注册原有 URL。
from . import assets, capability_list, completions, directory, feedback, previews, sessions, uploads # noqa: E402, F401
from . import assets, completions, directory, feedback, previews, sessions, uploads # noqa: E402, F401
from .shared import ( # noqa: E402, F401
CHAT_USER_ATTACHMENT_LIMIT,
CHAT_USER_ATTACHMENT_MAX_SIZE,
-31
View File
@@ -1,31 +0,0 @@
"""
api/chat/capability_list.py
用途:聊天端「知识库内容清单」查询接口,作为知识库未命中兜底回复按钮的数据源。
依赖:chat.shared(公共上下文与异常)、chat_bp、services.chat.capability_list。
逻辑:GET /api/chat/capability-list?agent_id=...,经 require_agent_permission 鉴权后
返回常用问题中该应用「能力清单条目」的标准答案;未配置时抛 404 业务错误。
"""
from __future__ import annotations
from .shared import * # noqa: F403
from . import chat_bp
from app.services.chat.capability_list import get_agent_capability_list
@chat_bp.route('/capability-list', methods=['GET'])
@require_agent_permission
def get_capability_list():
"""
获取当前应用的知识库内容清单。
用途:AI 回复命中知识库未命中兜底语句时,前端【知识库内容清单】按钮点击后调用。
核心逻辑:
1. require_agent_permission 从 query 读取 agent_id 并校验用户对该应用的访问权限;
2. 委托 services.chat.capability_list 返回「能力清单条目」标准答案;
3. 未配置时抛 code=CHAT.CAPABILITY_LIST_NOT_FOUND(404),前端按错误码本地化提示。
参数约束:agent_id 必须来自当前会话路由(当前聊天应用),禁止跨应用探测他人条目。
"""
agent = getattr(g, 'current_agent', None)
if agent is None:
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Missing agent context', http_status=500)
return jsonify(get_agent_capability_list(agent))
+46 -3
View File
@@ -7,9 +7,10 @@ backend/app/api/user/handlers.py
"""
from flask import Blueprint, request, jsonify, current_app
from sqlalchemy import and_, or_
from sqlalchemy.exc import DatabaseError, OperationalError
from sqlalchemy.exc import DatabaseError, IntegrityError, OperationalError
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.agent_category import serialize_agent_list_item, sort_agent_rows
from app.services.agent_registry.serialization import serialize_registry_fields
@@ -32,6 +33,11 @@ from .auth import (
)
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'])
def mark_wecom_deeplink_opened():
user = _get_current_user()
@@ -161,9 +167,46 @@ def submit_general_feedback():
raise ValidationError('chat_log_id not found')
if chat_log.user_id != user.id:
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)
# [STEP 3] 落库:flush 拿反馈 id → 按枚举序写图片关联(sort_order=下标)→ 逐个标记资产被引用 → commit;
# IntegrityError 兜底并发双挂(asset_id 唯一约束),回滚整单并转业务错误
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)
if notify_result.get('ok'):
current_app.logger.info('[feedback] group notification sent feedback_id=%s', row.id)
+9 -1
View File
@@ -10,7 +10,14 @@ backend/app/models/__init__.py
from app.models.agent import Agent, AgentDirectoryMember, AgentGuide, PermissionRequest
from app.models.base import Base, user_agent_permissions
from app.models.permission_role import PermissionRole, permission_role_agents, 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.department import Department
from app.models.linked_service import LinkedService
@@ -281,6 +288,7 @@ __all__ = [
'ChatToolRun',
'Feedback',
'GeneralFeedback',
'GeneralFeedbackImage',
'PermissionRequest',
'QuickQuestion',
'FaqHotCandidate',
+19
View File
@@ -135,3 +135,22 @@ class GeneralFeedback(Base):
# 关闭时间:记录何时被处理/关闭,用于「本月已关闭」统计
closed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=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)
+84 -1
View File
@@ -16,8 +16,9 @@ from sqlalchemy import asc, desc, func, or_
from app import db
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.services.file_assets.service import read_asset_bytes
USAGE_BY_USER_TOP_LIMIT = 50
APPLICATION_REPORT_PAGE_SIZE_MAX = 100
@@ -36,6 +37,16 @@ USAGE_LOW_AGENT_MAX_CHATS = 2
# 运营提醒:低使用应用最多返回条数
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 → 回溯天数(与前端下拉选项一致)
USAGE_RANGE_DAYS = {
'7d': 7,
@@ -557,6 +568,39 @@ def _apply_general_feedback_filters(query, query_params: dict[str, str]):
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]:
"""通用反馈列表(报表页)。"""
query = (
@@ -586,9 +630,48 @@ def list_general_feedbacks_report(query_params: dict[str, str]) -> list[dict]:
row['real_name'] = real_name
row['department'] = department
rows.append(row)
_attach_general_feedback_images(rows, [row['id'] for row in 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:
"""通用反馈计数。"""
query = db.session.query(GeneralFeedback).outerjoin(User, User.id == GeneralFeedback.user_id)
@@ -1,68 +0,0 @@
"""
services/chat/capability_list.py
用途:查询指定智能体在常用问题(QuickQuestion)中的「能力清单」条目标准答案。
依赖:models.QuickQuestion、core.errors.AppError、SQLAlchemy db。
逻辑:Dify 知识库未命中兜底回复会在前端展示【知识库内容清单】按钮;按钮点击后由
api/chat/capability_list.py 调用本模块,按 agent_id 过滤全局条目并返回标准答案。
管理端维护约定:条目标题形如「<应用名>·能力清单条目」,因此以标题含「能力清单」
作为识别关键字,应用归属仍以 agent_id 外键为准(禁止按标题前缀解析应用名)。
"""
from __future__ import annotations
from typing import Any
from app import db
from app.core.errors import AppError
from app.models import QuickQuestion
# 能力清单条目的标题识别关键字(管理端维护约定,见模块 docstring)。
CAPABILITY_LIST_TITLE_KEYWORD = '能力清单'
def get_agent_capability_list(agent: Any) -> dict[str, Any]:
"""
查询智能体的知识库内容清单条目。
用途:聊天端兜底回复【知识库内容清单】按钮的数据来源。
核心逻辑:
1. 仅匹配全局条目(user_id 为空)且归属当前 agent_id;
2. 标题须含「能力清单」关键字,且标准答案非空;
3. 多条命中时按 sort_order、id 取第一条,保证返回稳定。
Args:
agent: 已通过 require_agent_permission 鉴权的 Agent 模型实例,禁止传 None。
Returns:
含 id/agent_id/title/question/answer 的条目字典,answer 为标准答案原文。
Raises:
AppError: code=CHAT.CAPABILITY_LIST_NOT_FOUND,表示该应用尚未配置能力清单条目。
"""
agent_id = getattr(agent, 'id', None)
if not agent_id:
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Missing agent id', http_status=500)
entry = (
db.session.query(QuickQuestion)
.filter(
QuickQuestion.agent_id == agent_id,
QuickQuestion.user_id.is_(None),
QuickQuestion.title.contains(CAPABILITY_LIST_TITLE_KEYWORD),
QuickQuestion.answer.isnot(None),
QuickQuestion.answer != '',
)
.order_by(QuickQuestion.sort_order.asc(), QuickQuestion.id.asc())
.first()
)
if entry is None:
raise AppError(
code='CHAT.CAPABILITY_LIST_NOT_FOUND',
message='capability list entry is not configured for this agent',
http_status=404,
)
return {
'id': entry.id,
'agent_id': entry.agent_id,
'title': entry.title,
'question': entry.question,
'answer': entry.answer or '',
}
+4
View File
@@ -129,6 +129,10 @@ def build_feedback_markdown(feedback: GeneralFeedback, user: User | None) -> str
lines.append(f'>来源页面:{feedback.source_page}')
if 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 '-'])
if 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
+1 -9
View File
@@ -103,15 +103,7 @@
| ------------------ | ------ | ------------------------------------------------------------------------------------------------------------- |
| 意见反馈入库 | 已实现 | 用户在 Workspace/Chat 提交意见后写入 `general_feedbacks`,后台报表可查看 |
| 反馈企业微信群通知 | 已实现 | 反馈入库后通过 `WECOM_FEEDBACK_BOT_WEBHOOK` 即时推送到企业微信群;未配置 webhook 时静默跳过,不影响用户提交 |
## 知识库内容清单按钮(2026-10)
| 功能项 | 状态 | 说明 |
| ---------------------- | ------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 兜底回复触发识别 | 已实现 | Dify 知识库未命中兜底回复末尾追加 `[知识库能力清单]` 标记(兼容「内容清单」写法)时,前端识别并在语句结尾渲染【知识库内容清单】按钮;对无标记的已发布兜底原句按特征片段兜底识别,历史会话同样生效 |
| 标记展示剥离 | 已实现 | 渲染前从正文剥离标记及其前导标点(含流式半截标记裁剪),用户不会看到原始标记符号 |
| 能力清单标准答案查询 | 已实现 | `GET /api/chat/capability-list?agent_id=`(`require_agent_permission` 鉴权)返回常用问题中该应用「能力清单条目」(标题含「能力清单」的全局条目)的标准答案;未配置返回 `CHAT.CAPABILITY_LIST_NOT_FOUND` |
| 内容清单弹窗 | 已实现 | 点击按钮后按当前会话应用拉取标准答案并弹窗展示(Markdown 渲染);未配置时按错误码本地化提示,文案同步 zh-CN/zh-TW/en/th |
| 反馈截图附件 | 已实现 | 意见反馈支持粘贴/上传截图附件(每条最多 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`,
{ 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[]) =>
requestJson<{ deleted_count: number }>('/api/admin/database/chat_logs/batch-delete', {
method: 'POST',
@@ -4,6 +4,7 @@
* 依赖:useReportsAdmin、AdminListPage、AdminListTabs、element-plus、@element-plus/icons-vue。
* 逻辑:路由 /admin/reports/:table?。看板块用 ElCard;有表格的页签用 AdminListPage。
* 反馈页签用 AdminListTabs。筛选和分页沿用 composable 里的原状态。删除聊天日志用 Element 确认框。
* 意见反馈附图列为懒加载缩略图(composable 内 blob objectURL 缓存),页面附 lightbox 大图预览。
*/
<script setup lang="ts">
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 type { ApplicationReportItem, ApplicationSortKey, ApplicationUsageFilter } from '@/features/admin/types/report.types';
import { formatLocalDateTime } from '@/shared/utils/dateTime';
import type { FeedbackReportImage } from '../../api/admin.api';
import { useReportsAdmin } from './composables/useReportsAdmin';
const vLoading = ElLoading.directive;
@@ -181,6 +183,12 @@ const {
generalFeedbackTotal,
feedbackSummary,
closeFeedback,
feedbackImagePreview,
feedbackImageUrl,
loadFeedbackImage,
openFeedbackImagePreview,
closeFeedbackImagePreview,
stepFeedbackImagePreview,
feedbackTypeOptions,
feedbackModuleOptions,
feedbackSourceOptions,
@@ -231,6 +239,26 @@ const {
batchDeleteChatLogs,
} = 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[] = [
'name',
@@ -672,6 +700,16 @@ function isGeneralFeedbackContent(columnKey: string): boolean {
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 - 列字段
@@ -1779,6 +1817,25 @@ onMounted(() => {
</span>
</template>
</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'">
<ElButton
v-if="getFeedbackChatLogCell(row as ReportTableRow).type === 'link'"
@@ -1895,6 +1952,35 @@ onMounted(() => {
<ElButton @click="closeChatLogDetail">{{ t('admin.report.chatLog.close') }}</ElButton>
</template>
</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>
<style scoped>
@@ -5,9 +5,10 @@
* 逻辑:ReportsPage 调用本 composable;使用分析按用户服务端分页、按应用前端分页,页码状态交给页面的 ElPagination;
* 低使用应用优先消费后端 low_agents(含零使用启用应用),与应用运营口径对齐;
* 统计范围统一为开始/结束日期(默认近 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 { useRoute, useRouter } from 'vue-router';
import { ElMessageBox } from 'element-plus';
@@ -25,6 +26,7 @@ import {
getAdminUsageReport,
listAdminAgents,
} from '@/features/admin/api/admin.api';
import { requestBlob } from '@/shared/api/client';
import { loadReportLayoutPref, saveReportLayoutPref } from '@/shared/composables/useReportLayoutStorage';
import { buildOffsetPageButtons } from '@/shared/composables/useOffsetPagination';
import { useMessage } from '@/shared/composables/useMessage';
@@ -44,6 +46,7 @@ import type {
UsageReport,
} from '@/features/admin/types/report.types';
import type { AdminReportTableId } from '@/features/admin/types/admin.types';
import type { FeedbackReportImage } from '@/features/admin/api/admin.api';
/** 聊天日志报表固定展示列(顺序与产品约定一致;id 仅用于批量删除) */
const CHAT_LOGS_REPORT_KEYS = [
@@ -65,7 +68,8 @@ const CHAT_LOG_RISK_STATUS_OPTIONS = ['attention', 'review', 'responded'] as con
/**
* 报表列默认宽度:聊天日志前三列与 Token 收窄,提问/回答留宽,风险列居中紧凑;
* 意见反馈操作列保留按钮所需空间,防止中文文案按单字断行拉高整行。
* 意见反馈操作列保留按钮所需空间,防止中文文案按单字断行拉高整行;
* 意见反馈附图列按 3-4 张 40px 缩略图横排估宽。
* @param key - 列字段名
* @returns 像素宽度
*/
@@ -98,6 +102,8 @@ const defaultChatLogsColumnWidth = (key: string): number => {
return 240;
case 'actions':
return 112;
case 'images':
return 176;
default:
return 160;
}
@@ -381,6 +387,87 @@ export function useReportsAdmin() {
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 key = `admin.report.chatLog.risk.${status}`;
@@ -1048,6 +1135,7 @@ const visibleReportKeys = computed(() => {
'feedback_module',
'feedback_type',
'content',
'images',
'username',
'real_name',
'department',
@@ -1122,6 +1210,7 @@ const feedbackReportI18nMap: Record<string, FeedbackReportI18nPack> = {
/** 意见反馈 Tab 专用列名(覆盖通用列名,主要在关联跳转列) */
generalColumns: {
chat_log_id: 'Linked Chat',
images: 'Images',
},
/** 回答评价 Tab 列名:更易读、贴合评价语境 */
ratingColumns: {
@@ -1158,6 +1247,7 @@ const feedbackReportI18nMap: Record<string, FeedbackReportI18nPack> = {
},
generalColumns: {
chat_log_id: '\u5173\u8054\u804a\u5929',
images: '\u9644\u56fe',
},
ratingColumns: {
chat_log_id: '\u5173\u8054\u804a\u5929',
@@ -1193,6 +1283,7 @@ const feedbackReportI18nMap: Record<string, FeedbackReportI18nPack> = {
},
generalColumns: {
chat_log_id: '\u95dc\u806f\u804a\u5929',
images: '\u9644\u5716',
},
ratingColumns: {
chat_log_id: '\u95dc\u806f\u804a\u5929',
@@ -1228,6 +1319,7 @@ const feedbackReportI18nMap: Record<string, FeedbackReportI18nPack> = {
},
generalColumns: {
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: {
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);
}
if (key === 'images') {
// 附图列为对象数组:单元格由专用分支渲染缩略图;此处返回张数,供表头排序与 Excel 导出,避免出现 [object Object]
return Array.isArray(value) ? value.length : 0;
}
// format datetime fields in report table
if (typeof value === 'string' && (key.endsWith('_at') || key === 'created_at' || key === 'updated_at')) {
return formatReportDateTime(value);
@@ -1868,6 +1965,12 @@ watch([reportPageSize, issueQuestionTotal], () => {
feedbackSummary,
expandedFeedbackId,
closeFeedback,
feedbackImagePreview,
feedbackImageUrl,
loadFeedbackImage,
openFeedbackImagePreview,
closeFeedbackImagePreview,
stepFeedbackImagePreview,
feedbackTypeOptions,
feedbackModuleOptions,
feedbackSourceOptions,
@@ -9,7 +9,6 @@ import { requestJson } from '@/shared/api/client';
import type {
AssetHistorySearchResult,
AssetImageResolveResult,
ChatCapabilityListEntry,
ChatCrossAgentHistoryItem,
ChatMessage,
ChatQueryPreviewPage,
@@ -64,16 +63,6 @@ export const listChatMessages = async (conversationId: string, agentId: number)
: messages;
};
/**
* 获取当前应用的知识库内容清单(常用问题「能力清单条目」标准答案)。
* 用途:AI 回复命中知识库未命中兜底语句时,【知识库内容清单】按钮点击后调用。
* 核心逻辑:后端按 agent_id 过滤全局常用问题条目;未配置时抛 code=CHAT.CAPABILITY_LIST_NOT_FOUND。
* @param agentId - 当前聊天应用 ID(chatStore.currentAgentId),禁止传 0 或空值。
* @returns 含标准答案 answer 的清单条目。
*/
export const getAgentCapabilityList = (agentId: number) =>
requestJson<ChatCapabilityListEntry>(`/api/chat/capability-list?agent_id=${agentId}`, auth());
export const saveLocalChatMessage = (payload: Record<string, unknown>) =>
requestJson<{ conversation_id?: string; chat_log_id?: number }>('/api/chat/messages/local', {
method: 'POST',
@@ -21,8 +21,6 @@ import { useRoute } from 'vue-router';
import { useAuthStore } from '@/features/auth/stores/auth.store';
import { Maximize2 } from 'lucide-vue-next';
import ChatShell from '@/shared/layouts/ChatShell.vue';
import ChatSidebar from '@/features/chat/components/ChatSidebar.vue';
@@ -52,7 +52,6 @@ async function handleQueryPreviewAssetImage(assetId: string, assetName: string)
/>
<GeneralFeedbackDialog
v-model="page.showGeneralFeedbackDialog"
:auth-headers="getAuthHeaders()"
source-page="chat"
:chat-log-id="page.currentGeneralFeedbackChatLogId"
@submitted="onFeedbackSubmitted"
@@ -7,19 +7,12 @@
* 助手 Markdown 排版在本组件内收口:全局 base 只恢复标题字重,列表序号/圆点、
* 层级缩进与标题字号层级由 scoped 样式统一补齐,避免回答渲染成无结构平铺文本。
* 兼容:同时承接采购合同审查、库存映射、订单提取和 Mermaid 展示。
* 知识库未命中兜底回复按原始 content 检测触发标记,在正文下方渲染【知识库内容清单】按钮,
* 点击后弹窗展示常用问题「能力清单条目」标准答案。
*/
<script setup lang="ts">
import { computed, nextTick, onMounted, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { BookOpen, Check, Copy, Download, Edit2, Eye, LayoutGrid, MessageSquareText, RotateCw, X } from 'lucide-vue-next';
import { Check, Copy, Download, Edit2, Eye, LayoutGrid, MessageSquareText, RotateCw, X } from 'lucide-vue-next';
import { useAuthStore } from '@/features/auth/stores/auth.store';
import { useMessage } from '@/shared/composables/useMessage';
import { useChatStore } from '../../stores/chat.store';
import { getAgentCapabilityList } from '../../api/chat.api';
import { hasCapabilityListTrigger } from '../../utils/capabilityList';
import type { ChatCapabilityListEntry } from '../../types/chat.types';
import LeaveMessageBlock, { type LeaveMessageHandlers } from './LeaveMessageBlock.vue';
import ChatMessageAttachmentList from './ChatMessageAttachmentList.vue';
import MaintenanceDeviceResultCard from './MaintenanceDeviceResultCard.vue';
@@ -223,45 +216,6 @@ watch(renderedMarkdown, () => { void renderMermaidCharts(); });
const inlineDownloadFiles = computed(() => (
message.role === 'assistant' ? handlers.getInlineDownloadFiles(message.content).files : []
));
// [知识库内容清单]:触发检测基于原始 content(标记剥离只发生在展示文本层),历史会话同样生效。
const chatStore = useChatStore();
const { error: showCapabilityError } = useMessage();
const capabilityListButtonVisible = computed(() => (
message.role === 'assistant' && hasCapabilityListTrigger(message.content)
));
const capabilityListLoading = ref(false);
const capabilityListEntry = ref<ChatCapabilityListEntry | null>(null);
/**
* 拉取并打开知识库内容清单弹窗。
* AI 触发时机:知识库未命中兜底回复正文下方的【知识库内容清单】按钮被点击时调用。
* 核心逻辑:按当前会话应用(chatStore.currentAgentId)请求常用问题「能力清单条目」标准答案,
* 成功后以弹窗展示;失败时优先复用 requestJson 抛出 BusinessError 的错误码本地化文案。
* 参数约束:agentId 一律取自路由级 chat store,组件不接收外部传入的应用 ID,禁止跨应用查询。
*/
async function openCapabilityListDialog(): Promise<void> {
if (capabilityListLoading.value) return;
const agentId = Number(chatStore.currentAgentId || 0);
if (!agentId) {
showCapabilityError(t('chat.capabilityList.notFound'));
return;
}
capabilityListLoading.value = true;
try {
capabilityListEntry.value = await getAgentCapabilityList(agentId);
} catch (error) {
showCapabilityError(error instanceof Error ? error.message : t('chat.capabilityList.notFound'));
} finally {
capabilityListLoading.value = false;
}
}
/** 关闭知识库内容清单弹窗并清空条目,避免下次打开闪现旧内容。 */
function closeCapabilityListDialog(): void {
capabilityListEntry.value = null;
}
const shippingParseReviewHandlers = computed<ShippingParseReviewHandlers>(() => ({
getPayload: shippingHandlers.getParseReviewPayload,
updateHeader: shippingHandlers.updateHeader,
@@ -911,18 +865,6 @@ function handleInlineDownload(file: InlineDownloadFile): void {
</button>
</div>
<div v-if="capabilityListButtonVisible" class="mt-4">
<button
type="button"
class="inline-flex items-center gap-2 rounded-xl border border-brand-200 bg-brand-50 px-3 py-2 text-xs font-medium text-brand-700 transition hover:bg-brand-100 disabled:cursor-not-allowed disabled:opacity-60"
:disabled="capabilityListLoading"
@click="openCapabilityListDialog"
>
<BookOpen class="h-3.5 w-3.5" />
{{ $t('chat.capabilityList.button') }}
</button>
</div>
</div>
</div>
@@ -1193,31 +1135,6 @@ function handleInlineDownload(file: InlineDownloadFile): void {
</div>
</div>
</Teleport>
<Teleport to="body">
<div
v-if="capabilityListEntry"
class="dialog-overlay z-[130] items-center"
@click.self="closeCapabilityListDialog"
>
<div class="dialog-panel flex max-h-[88vh] w-[min(96vw,760px)] flex-col">
<div class="dialog-header">
<div>
<h3 class="section-title">{{ $t('chat.capabilityList.dialogTitle') }}</h3>
<p class="section-desc mt-1">{{ capabilityListEntry.title }}</p>
</div>
<button type="button" class="btn-icon-ds" :aria-label="$t('common.close')" @click="closeCapabilityListDialog">
<X class="h-5 w-5" />
</button>
</div>
<div class="dialog-body min-h-0 flex-1 overflow-auto border-t-0 pt-4">
<div
class="markdown-body chat-markdown min-w-0 break-words text-sm leading-relaxed"
v-html="handlers.renderMarkdown(capabilityListEntry.answer)"
/>
</div>
</div>
</div>
</Teleport>
</template>
<style scoped>
@@ -17,7 +17,6 @@ import {
parseFileCheckExcelRunId,
rewriteFileCheckExcelLinksForDisplay,
} from '../utils/fileCheckExcelDownload';
import { stripCapabilityListMarker } from '../utils/capabilityList';
marked.setOptions({ gfm: true, breaks: true });
@@ -473,9 +472,7 @@ export function createChatPageMarkdownApi(ctx: ChatPageMarkdownContext) {
/**
* 将聊天正文转换为展示 HTML,并在渲染前剥离内嵌文件 JSON 块。
* 核心逻辑:先抽取 FILE_START/FILE_END 文件,再剥离知识库未命中兜底回复的 [知识库能力清单]
* 触发标记(按钮由 ChatMessageBubble 按原始 content 渲染),最后走既有 Markdown 清洗与
* marked 渲染,保证聊天气泡只展示可读文本。
* 核心逻辑:先抽取 FILE_START/FILE_END 文件,再走既有 Markdown 清洗与 marked 渲染,保证聊天气泡只展示可读文本。
* @param text - 原始聊天文本。
* @returns 供 v-html 使用的安全展示字符串。
*/
@@ -483,7 +480,7 @@ export function createChatPageMarkdownApi(ctx: ChatPageMarkdownContext) {
if (!text) return '';
const extracted = safeExtractInlineDownloadFiles(text);
const displayText = rewriteFileCheckExcelLinksForDisplay(
ctx.prepareMarkdownDisplayText(stripCapabilityListMarker(extracted.cleanedText)),
ctx.prepareMarkdownDisplayText(extracted.cleanedText),
);
try {
const rendered = marked.parse(displayText, { renderer: chatMarkdownRenderer });
@@ -373,12 +373,3 @@ export interface ChatQueryPreviewPage {
has_more: boolean;
query?: string;
}
/** 知识库内容清单条目:常用问题中「<应用名>·能力清单条目」的标准答案(GET /api/chat/capability-list)。 */
export interface ChatCapabilityListEntry {
id: number;
agent_id: number;
title: string;
question: string;
answer: string;
}
@@ -1,55 +0,0 @@
/**
* features/chat/utils/capabilityList.spec.ts
* 用途:验证知识库未命中兜底回复的触发识别与标记剥离规则。
* 依赖:vitest、capabilityList 纯函数。
* 逻辑:覆盖完整标记、兼容写法、历史无标记兜底原句、流式半截标记与普通消息不误伤五类场景。
*/
import { describe, expect, it } from 'vitest';
import { hasCapabilityListTrigger, stripCapabilityListMarker } from './capabilityList';
describe('hasCapabilityListTrigger', () => {
it('命中完整标记(圈2 草稿形态)', () => {
expect(hasCapabilityListTrigger('持续补充; [知识库能力清单]。')).toBe(true);
});
it('兼容「内容清单」写法', () => {
expect(hasCapabilityListTrigger('持续补充;[知识库内容清单]。')).toBe(true);
});
it('命中无标记的历史兜底原句(圈1 已发布形态)', () => {
expect(hasCapabilityListTrigger(
'这个问题超出了当前知识库的收录范围,所以没能找到答案。欢迎点击页面左下角的【意见反馈】按钮,把想查询的内容告诉我们,我们会根据反馈持续补充;',
)).toBe(true);
});
it('流式阶段未闭合的半截标记也视为触发', () => {
expect(hasCapabilityListTrigger('持续补充; [知识库能力清')).toBe(true);
});
it('普通回答不误伤', () => {
expect(hasCapabilityListTrigger('公司年假共 10 天,请查看 [考勤制度] 文档。')).toBe(false);
expect(hasCapabilityListTrigger('')).toBe(false);
});
});
describe('stripCapabilityListMarker', () => {
it('剥离完整标记并清理前导分号与句末句号', () => {
expect(stripCapabilityListMarker('我们会根据反馈持续补充; [知识库能力清单]。'))
.toBe('我们会根据反馈持续补充');
});
it('剥离中文分号与句号组合', () => {
expect(stripCapabilityListMarker('我们会根据反馈持续补充;[知识库内容清单]。'))
.toBe('我们会根据反馈持续补充');
});
it('裁剪流式阶段未闭合的半截标记', () => {
expect(stripCapabilityListMarker('我们会根据反馈持续补充; [知识库能力清'))
.toBe('我们会根据反馈持续补充;');
});
it('无标记文本原样返回', () => {
const text = '这个问题超出了当前知识库的收录范围,所以没能找到答案。';
expect(stripCapabilityListMarker(text)).toBe(text);
});
});
@@ -1,47 +0,0 @@
/**
* features/chat/utils/capabilityList.ts
* 用途:识别 Dify 知识库未命中兜底回复中的「知识库内容清单」触发条件,并负责展示文本清洗。
* 依赖:无(纯函数,供 useChatPageMarkdown 与 ChatMessageBubble 复用)。
* 逻辑:Dify「直接回复」节点在兜底语句末尾追加 [知识库能力清单] 标记时,前端据此渲染按钮并
* 从正文剥离标记;对未加标记的已发布兜底语句(旧回复、历史会话),按兜底语句稳定特征
* 片段兜底识别。检测作用于原始 content,剥离只影响 Markdown 展示文本。
*/
/** Dify 兜底回复末尾的触发标记,兼容「能力清单 / 内容清单」两种写法及其前导标点与句末句号。 */
const CAPABILITY_LIST_MARKER_REGEX = /\s*[;;,,、]?\s*\[知识库(?:能力|内容)清单\]\s*。?/g;
/** 流式渲染阶段可能只到达一半的未闭合标记(如「[知识库能力清」),按前缀裁剪避免原始符号闪现。 */
const CAPABILITY_LIST_MARKER_PARTIAL_REGEX = /\s*\[知识库[^[\]]*$/;
/** 已上线兜底语句的稳定特征片段(圈1 原句「这个问题超出了当前知识库的收录范围…」)。 */
const KB_FALLBACK_PHRASE = '超出了当前知识库的收录范围';
/**
* 判断一条助手消息是否应展示【知识库内容清单】按钮。
* AI 触发时机:渲染助手消息正文下方按钮前调用,用于决定按钮显隐。
* 核心逻辑:命中完整标记(含流式半截标记)或兜底语句特征片段即视为触发;用户消息由调用方
* 保证不进入本判断。
* 参数约束:传入消息原始 content(未剥标记),禁止传入已渲染 HTML。
* @param content - 消息原始文本。
* @returns 是否展示【知识库内容清单】按钮。
*/
export function hasCapabilityListTrigger(content: string): boolean {
const raw = String(content || '');
if (!raw) return false;
if (raw.includes(KB_FALLBACK_PHRASE)) return true;
return /\[知识库(?:能力|内容)清单\]/.test(raw) || /\[知识库[^[\]]*$/.test(raw);
}
/**
* 从展示文本中剥离「知识库内容清单」触发标记,保留其余正文。
* 核心逻辑:先移除完整标记(连同其前导标点与句末句号,避免留下「; 。」类残渣),再裁剪
* 流式阶段未闭合的半截标记;无标记时原样返回。
* 参数约束:仅用于 Markdown 渲染前的展示文本清洗,不落库、不回写消息 content。
* @param text - 待渲染的展示文本。
* @returns 剥离标记后的展示文本。
*/
export function stripCapabilityListMarker(text: string): string {
const raw = String(text || '');
if (!raw) return '';
return raw.replace(CAPABILITY_LIST_MARKER_REGEX, '').replace(CAPABILITY_LIST_MARKER_PARTIAL_REGEX, '');
}
@@ -13,7 +13,6 @@ import 'element-plus/theme-chalk/dark/css-vars.css';
import '@/shared/styles/element-theme.css';
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
import GeneralFeedbackDialog from '@/shared/components/GeneralFeedbackDialog.vue';
import { getAuthHeaders } from '@/shared/utils/auth';
import { WORKSPACE_KEY } from '../composables/workspace.context';
const ws = inject(WORKSPACE_KEY)! as any;
@@ -106,7 +105,6 @@ function submitPassword(): void {
/>
<GeneralFeedbackDialog
v-model="ws.showGeneralFeedbackDialog"
:auth-headers="getAuthHeaders()"
source-page="workspace"
@submitted="ws.msg.success('反馈提交成功')"
/>
+1
View File
@@ -2369,6 +2369,7 @@
"markClosed": "Mark closed",
"closed": "Closed",
"closedOk": "Marked as closed",
"closePreview": "Close preview",
"summary": {
"pending": "Pending",
"pendingHint": "Feedback to follow up",
-5
View File
@@ -3604,11 +3604,6 @@
"libraryNotConfigured": "Fixed-asset image library is not configured. Contact an admin.",
"noPhotoUploaded": "No photo has been uploaded by the device admin yet~"
},
"capabilityList": {
"button": "KB Content List",
"dialogTitle": "Knowledge Base Content List",
"notFound": "No knowledge base content list is configured for this agent"
},
"queryPreview": {
"title": "Full query result preview",
"viewAll": "View full preview",
+3 -1
View File
@@ -151,7 +151,6 @@
"AUTH_SSO_ASSERTION_ISSUE_FAILED": "The peer-service login assertion could not be issued. Please retry.",
"AUTH_FORBIDDEN": "You do not have permission to perform this action.",
"CHAT.USER_ATTACHMENTS_LIMIT_EXCEEDED": "Too many attachments (maximum 200). Remove some and try again.",
"CHAT.CAPABILITY_LIST_NOT_FOUND": "No knowledge base content list is configured for this agent. Ask an administrator to maintain its 'capability list' FAQ entry.",
"CONTRACT_PAYMENT_FORBIDDEN": "You do not have access to contract payment alerts.",
"CONTRACT_PAYMENT_ADMIN_REQUIRED": "Only administrators can sync, scan, or send contract payment alerts.",
"CONTRACT_PAYMENT_ATTACHMENT_UNAVAILABLE": "The contract file was removed and could not be downloaded again from the source system. Sync OA data and try again.",
@@ -298,6 +297,9 @@
"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_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_EXPIRED": "File asset has expired.",
"FILE_ASSET_ALREADY_REFERENCED": "File asset is already referenced and cannot be deleted.",
+10 -1
View File
@@ -26,5 +26,14 @@
},
"cancel": "Cancel",
"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"
}
}
+1
View File
@@ -2351,6 +2351,7 @@
"markClosed": "ทำเครื่องหมายว่าปิดแล้ว",
"closed": "ปิดแล้ว",
"closedOk": "ทำเครื่องหมายว่าปิดแล้ว",
"closePreview": "ปิดตัวอย่าง",
"summary": {
"pending": "รอดำเนินการ",
"pendingHint": "ข้อเสนอแนะรอติดตาม",
-5
View File
@@ -3604,11 +3604,6 @@
"libraryNotConfigured": "ยังไม่ได้ตั้งค่าคลังรูปภาพสินทรัพย์ถาวร กรุณาติดต่อผู้ดูแลระบบ",
"noPhotoUploaded": "ผู้ดูแลอุปกรณ์ยังไม่ได้อัปโหลดรูปภาพ~"
},
"capabilityList": {
"button": "รายการเนื้อหาคลังความรู้",
"dialogTitle": "รายการเนื้อหาคลังความรู้",
"notFound": "ยังไม่ได้ตั้งค่ารายการเนื้อหาคลังความรู้สำหรับเอเจนต์นี้"
},
"queryPreview": {
"title": "ดูผลลัพธ์การค้นหาทั้งหมด",
"viewAll": "ดูตัวอย่างทั้งหมด",
+3 -1
View File
@@ -151,7 +151,6 @@
"AUTH_SSO_ASSERTION_ISSUE_FAILED": "ไม่สามารถออกข้อมูลยืนยันการเข้าสู่ระบบสำหรับบริการในผลิตภัณฑ์ได้ โปรดลองใหม่",
"AUTH_FORBIDDEN": "คุณไม่มีสิทธิ์ดำเนินการนี้",
"CHAT.USER_ATTACHMENTS_LIMIT_EXCEEDED": "ไฟล์แนบเกินจำนวนที่อนุญาต (สูงสุด 200 ไฟล์) โปรดลดจำนวนแล้วลองใหม่",
"CHAT.CAPABILITY_LIST_NOT_FOUND": "ยังไม่ได้ตั้งค่ารายการเนื้อหาคลังความรู้สำหรับเอเจนต์นี้ โปรดให้ผู้ดูแลระบบเพิ่มรายการ 'capability list' ในคำถามที่พบบ่อย",
"CONTRACT_PAYMENT_FORBIDDEN": "คุณไม่มีสิทธิ์เข้าถึงการแจ้งเตือนการชำระเงินตามสัญญา",
"CONTRACT_PAYMENT_ADMIN_REQUIRED": "เฉพาะผู้ดูแลระบบเท่านั้นที่ซิงก์ สแกน หรือส่งการแจ้งเตือนการชำระเงินตามสัญญาได้",
"CONTRACT_PAYMENT_ATTACHMENT_UNAVAILABLE": "ไฟล์ต้นฉบับของสัญญาถูกลบไปแล้ว และไม่สามารถดาวน์โหลดใหม่จากระบบต้นทางได้ โปรดซิงก์ข้อมูล OA แล้วลองอีกครั้ง",
@@ -298,6 +297,9 @@
"FILE_ASSET_FORBIDDEN": "คุณไม่มีสิทธิ์เข้าถึงไฟล์นี้",
"FILE_ASSET_UPLOAD_FAILED": "อัปโหลดไฟล์ล้มเหลว โปรดลองใหม่ภายหลัง",
"FILE_ASSET_INVALID_TYPE": "ชนิดไฟล์ไม่รองรับ",
"FEEDBACK_IMAGE_INVALID": "รูปภาพข้อเสนอแนะไม่ถูกต้องหรือถูกใช้งานแล้ว",
"FEEDBACK_IMAGE_TOO_MANY": "จำนวนรูปภาพข้อเสนอแนะเกินกำหนด",
"FEEDBACK_IMAGE_NOT_FOUND": "ไม่พบรูปภาพข้อเสนอแนะ",
"FILE_ASSET_SIZE_EXCEEDED": "ขนาดไฟล์เกินขีดจำกัด",
"FILE_ASSET_EXPIRED": "ไฟล์หมดอายุแล้ว",
"FILE_ASSET_ALREADY_REFERENCED": "ไฟล์ถูกอ้างอิงโดยธุรกิจแล้ว ไม่สามารถลบได้",
+10 -1
View File
@@ -26,5 +26,14 @@
},
"cancel": "ยกเลิก",
"submitting": "กำลังส่ง...",
"submit": "ส่ง"
"submit": "ส่ง",
"upload": {
"addImage": "เพิ่มรูปภาพ",
"pasteHint": "วางภาพหน้าจอ (Ctrl+V) หรือคลิกเพื่อเพิ่ม สูงสุด 5 รูป",
"maxCount": "เพิ่มได้สูงสุด {count} รูป",
"maxSize": "รูปภาพเดียวต้องไม่เกิน {size}MB",
"invalidType": "รองรับเฉพาะไฟล์ png / jpg / jpeg / webp",
"uploadFailed": "อัปโหลดรูปภาพไม่สำเร็จ กรุณาลองอีกครั้ง",
"remove": "นำรูปภาพออก"
}
}
+1
View File
@@ -2482,6 +2482,7 @@
"markClosed": "标记已关闭",
"closed": "已关闭",
"closedOk": "已标记关闭",
"closePreview": "关闭预览",
"summary": {
"pending": "待处理",
"pendingHint": "待跟进反馈",
-5
View File
@@ -3604,11 +3604,6 @@
"libraryNotConfigured": "当前系统暂未配置固定资产图片文档库,暂时无法查看图片,请联系管理员处理。",
"noPhotoUploaded": "设备管理员还未上传照片~"
},
"capabilityList": {
"button": "知识库内容清单",
"dialogTitle": "知识库内容清单",
"notFound": "该应用尚未配置知识库内容清单"
},
"queryPreview": {
"title": "查询结果全量预览",
"viewAll": "查看全部预览",
+3 -1
View File
@@ -151,7 +151,6 @@
"AUTH_SSO_ASSERTION_ISSUE_FAILED": "平级服务登录声明签发失败,请重试。",
"AUTH_FORBIDDEN": "你没有权限执行该操作。",
"CHAT.USER_ATTACHMENTS_LIMIT_EXCEEDED": "附件数量超过上限(最多 200 个),请减少后重试。",
"CHAT.CAPABILITY_LIST_NOT_FOUND": "该应用尚未配置知识库内容清单,请在管理端常用问题中为它维护「能力清单条目」。",
"CONTRACT_PAYMENT_FORBIDDEN": "你没有合同付款预警的访问权限。",
"CONTRACT_PAYMENT_ADMIN_REQUIRED": "仅管理员可执行合同付款预警的同步、扫描或发送操作。",
"CONTRACT_PAYMENT_ATTACHMENT_UNAVAILABLE": "合同原文已被清理,且无法从原系统重新下载。请先同步 OA 数据后再试。",
@@ -298,6 +297,9 @@
"FILE_ASSET_FORBIDDEN": "无权访问该文件资产。",
"FILE_ASSET_UPLOAD_FAILED": "文件上传失败,请稍后重试。",
"FILE_ASSET_INVALID_TYPE": "不支持的文件类型。",
"FEEDBACK_IMAGE_INVALID": "反馈图片无效或已被使用。",
"FEEDBACK_IMAGE_TOO_MANY": "反馈图片数量超过上限。",
"FEEDBACK_IMAGE_NOT_FOUND": "反馈图片不存在。",
"FILE_ASSET_SIZE_EXCEEDED": "文件大小超过限制。",
"FILE_ASSET_EXPIRED": "文件资产已过期。",
"FILE_ASSET_ALREADY_REFERENCED": "文件已被业务引用,无法删除。",
+10 -1
View File
@@ -26,5 +26,14 @@
},
"cancel": "取消",
"submitting": "提交中...",
"submit": "提交"
"submit": "提交",
"upload": {
"addImage": "添加图片",
"pasteHint": "支持粘贴截图(Ctrl+V)或点击添加,最多 5 张",
"maxCount": "最多添加 {count} 张图片",
"maxSize": "单张图片不能超过 {size}MB",
"invalidType": "仅支持 png / jpg / jpeg / webp 格式图片",
"uploadFailed": "图片上传失败,请重试",
"remove": "移除图片"
}
}
+1
View File
@@ -2351,6 +2351,7 @@
"markClosed": "標記已關閉",
"closed": "已關閉",
"closedOk": "已標記關閉",
"closePreview": "關閉預覽",
"summary": {
"pending": "待處理",
"pendingHint": "待跟進反饋",
-5
View File
@@ -3604,11 +3604,6 @@
"libraryNotConfigured": "當前系統暫未設定固定資產圖片文件庫,暫時無法查看圖片,請聯絡管理員處理。",
"noPhotoUploaded": "設備管理員尚未上傳照片~"
},
"capabilityList": {
"button": "知識庫內容清單",
"dialogTitle": "知識庫內容清單",
"notFound": "該應用尚未配置知識庫內容清單"
},
"queryPreview": {
"title": "查詢結果全量預覽",
"viewAll": "查看全部預覽",
+3 -1
View File
@@ -151,7 +151,6 @@
"AUTH_SSO_ASSERTION_ISSUE_FAILED": "平級服務登入聲明簽發失敗,請重試。",
"AUTH_FORBIDDEN": "你沒有權限執行此操作。",
"CHAT.USER_ATTACHMENTS_LIMIT_EXCEEDED": "附件數量超過上限(最多 200 個),請減少後重試。",
"CHAT.CAPABILITY_LIST_NOT_FOUND": "該應用尚未配置知識庫內容清單,請在管理端常用問題中為它維護「能力清單條目」。",
"CONTRACT_PAYMENT_FORBIDDEN": "你沒有合約付款預警的存取權限。",
"CONTRACT_PAYMENT_ADMIN_REQUIRED": "僅管理員可執行合約付款預警的同步、掃描或發送操作。",
"CONTRACT_PAYMENT_ATTACHMENT_UNAVAILABLE": "合約原文已被清理,且無法從原系統重新下載。請先同步 OA 資料後再試。",
@@ -298,6 +297,9 @@
"FILE_ASSET_FORBIDDEN": "無權存取該檔案資產。",
"FILE_ASSET_UPLOAD_FAILED": "檔案上傳失敗,請稍後重試。",
"FILE_ASSET_INVALID_TYPE": "不支援的檔案類型。",
"FEEDBACK_IMAGE_INVALID": "迴饋圖片無效或已被使用。",
"FEEDBACK_IMAGE_TOO_MANY": "迴饋圖片數量超過上限。",
"FEEDBACK_IMAGE_NOT_FOUND": "迴饋圖片不存在。",
"FILE_ASSET_SIZE_EXCEEDED": "檔案大小超過限制。",
"FILE_ASSET_EXPIRED": "檔案資產已過期。",
"FILE_ASSET_ALREADY_REFERENCED": "檔案已被業務引用,無法刪除。",
+10 -1
View File
@@ -26,5 +26,14 @@
},
"cancel": "取消",
"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
* 用途:工作台和对话里的意见反馈提交弹窗。
* 依赖:element-plus、/api/user/feedback。
* 逻辑:由 FeedbackPage 和 WorkspaceModals 打开。类型、模块和内容仍提交原接口。
* 通用意见反馈提交弹窗(Element Plus 版)。
* 用途:收集反馈类型/模块/内容,并支持粘贴(Ctrl+V)或点击选择图片;图片先经文件资产接口
* 上传换取 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 { Loader2, Plus, X } from 'lucide-vue-next';
import {
ElButton,
ElDialog,
ElForm,
ElFormItem,
ElInput,
ElMessage,
ElOption,
ElRadioButton,
ElRadioGroup,
ElSegmented,
ElSelect,
} from 'element-plus';
import 'element-plus/dist/index.css';
import 'element-plus/theme-chalk/dark/css-vars.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 {
modelValue: boolean;
authHeaders?: Record<string, string>;
sourcePage?: string;
chatLogId?: number | null;
}
const props = withDefaults(defineProps<Props>(), {
authHeaders: () => ({}),
sourcePage: 'unknown',
chatLogId: null,
});
@@ -43,6 +63,11 @@ const emit = defineEmits<{
const { t, locale } = useI18n({ useScope: 'global' });
const visible = computed({
get: () => props.modelValue,
set: (v: boolean) => emit('update:modelValue', v),
});
const typeOptions = computed(() => [
t('feedback.type.featureSuggestion'),
t('feedback.type.issueReport'),
@@ -61,8 +86,132 @@ const selectedModule = ref<string>(t('feedback.module.knowledgeBase'));
const content = ref('');
const submitting = ref(false);
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 = () => {
emit('update:modelValue', false);
@@ -74,12 +223,14 @@ const resetForm = () => {
content.value = '';
error.value = '';
submitting.value = false;
cleanupImages();
};
watch(
() => props.modelValue,
(visible) => {
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 () => {
if (!canSubmit.value) {
error.value = t('feedback.msg.fillContent');
@@ -104,31 +263,25 @@ const submitFeedback = async () => {
feedback_module: selectedModule.value,
content: content.value.trim(),
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) {
payload.chat_log_id = props.chatLogId;
}
const res = await fetch('/api/user/feedback', {
await requestJson<void>('/api/user/feedback', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...props.authHeaders,
},
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) {
error.value = data?.error || t('feedback.msg.submitFailed');
return;
}
emit('submitted');
closeDialog();
} catch {
error.value = t('feedback.msg.submitFailed');
} catch (e) {
error.value = e instanceof BusinessError ? e.message : t('feedback.msg.submitFailed');
} finally {
submitting.value = false;
}
@@ -137,53 +290,105 @@ const submitFeedback = async () => {
<template>
<ElDialog
:model-value="modelValue"
v-model="visible"
:title="t('feedback.title')"
width="680px"
align-center
width="640px"
append-to-body
:close-on-click-modal="false"
@update:model-value="emit('update:modelValue', $event)"
>
<ElForm label-position="top">
<ElFormItem :label="t('feedback.labels.type')">
<ElRadioGroup v-model="selectedType">
<ElRadioButton v-for="item in typeOptions" :key="item" :value="item">{{ item }}</ElRadioButton>
</ElRadioGroup>
</ElFormItem>
<ElFormItem :label="t('feedback.labels.module')">
<ElSelect v-model="selectedModule" class="feedback-module">
<div class="space-y-5" @paste="onPaste">
<div class="space-y-1.5">
<div class="text-sm font-medium text-secondary">{{ t('feedback.labels.type') }}</div>
<ElSegmented v-model="selectedType" :options="typeOptions" />
</div>
<div class="space-y-1.5">
<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" />
</ElSelect>
</ElFormItem>
<ElFormItem :label="t('feedback.labels.content')" required>
</div>
<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
v-model="content"
type="textarea"
:rows="5"
maxlength="2000"
:maxlength="2000"
show-word-limit
resize="none"
:placeholder="t('feedback.placeholder.content')"
/>
<div v-if="error" class="feedback-error">{{ error }}</div>
</ElFormItem>
</ElForm>
<div class="mt-1 flex flex-wrap items-center gap-2">
<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>
<ElButton :disabled="submitting" @click="closeDialog">{{ t('feedback.cancel') }}</ElButton>
<ElButton type="primary" :loading="submitting" :disabled="!canSubmit" @click="submitFeedback">
<ElButton :disabled="submitting" @click="closeDialog">
{{ t('feedback.cancel') }}
</ElButton>
<ElButton
type="primary"
:loading="submitting"
:disabled="!canSubmit"
@click="submitFeedback"
>
{{ submitting ? t('feedback.submitting') : t('feedback.submit') }}
</ElButton>
</template>
</ElDialog>
</template>
<style scoped>
.feedback-module {
width: 100%;
}
.feedback-error {
margin-top: 8px;
color: var(--el-color-danger);
}
</style>