diff --git a/backend/app/api/admin/reports.py b/backend/app/api/admin/reports.py index e9adcd31..d93a9035 100644 --- a/backend/app/api/admin/reports.py +++ b/backend/app/api/admin/reports.py @@ -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//images//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 diff --git a/backend/app/api/user/handlers.py b/backend/app/api/user/handlers.py index b881397a..0fcb39ef 100644 --- a/backend/app/api/user/handlers.py +++ b/backend/app/api/user/handlers.py @@ -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) diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.py index 5a8c04bf..934091d0 100644 --- a/backend/app/models/__init__.py +++ b/backend/app/models/__init__.py @@ -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', diff --git a/backend/app/models/chat.py b/backend/app/models/chat.py index 5019949d..80615f86 100644 --- a/backend/app/models/chat.py +++ b/backend/app/models/chat.py @@ -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) diff --git a/backend/app/services/admin/report_service.py b/backend/app/services/admin/report_service.py index dd8663d0..065dadec 100644 --- a/backend/app/services/admin/report_service.py +++ b/backend/app/services/admin/report_service.py @@ -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) diff --git a/backend/app/services/feedback_notify.py b/backend/app/services/feedback_notify.py index 4b38eb01..73d13091 100644 --- a/backend/app/services/feedback_notify.py +++ b/backend/app/services/feedback_notify.py @@ -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})']) diff --git a/backend/migrations/versions/7e5bc4bc0cbc_合并意见反馈附图表与设备验收评审两条_alembic_头.py b/backend/migrations/versions/7e5bc4bc0cbc_合并意见反馈附图表与设备验收评审两条_alembic_头.py new file mode 100644 index 00000000..9a0f66cb --- /dev/null +++ b/backend/migrations/versions/7e5bc4bc0cbc_合并意见反馈附图表与设备验收评审两条_alembic_头.py @@ -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 diff --git a/backend/migrations/versions/c375467a21f9_合并用户多角色与意见反馈附图两条_alembic_头.py b/backend/migrations/versions/c375467a21f9_合并用户多角色与意见反馈附图两条_alembic_头.py new file mode 100644 index 00000000..48c88b96 --- /dev/null +++ b/backend/migrations/versions/c375467a21f9_合并用户多角色与意见反馈附图两条_alembic_头.py @@ -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 diff --git a/backend/migrations/versions/sxw4m73amjyh_add_general_feedback_images.py b/backend/migrations/versions/sxw4m73amjyh_add_general_feedback_images.py new file mode 100644 index 00000000..150e9dee --- /dev/null +++ b/backend/migrations/versions/sxw4m73amjyh_add_general_feedback_images.py @@ -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 ### diff --git a/backend/tests/api/test_general_feedback_api.py b/backend/tests/api/test_general_feedback_api.py new file mode 100644 index 00000000..e181031b --- /dev/null +++ b/backend/tests/api/test_general_feedback_api.py @@ -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 diff --git a/backend/tests/services/test_feedback_notify.py b/backend/tests/services/test_feedback_notify.py new file mode 100644 index 00000000..2d8667df --- /dev/null +++ b/backend/tests/services/test_feedback_notify.py @@ -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 diff --git a/docs/funclist.md b/docs/funclist.md index 524462a2..650b0dcc 100644 --- a/docs/funclist.md +++ b/docs/funclist.md @@ -103,6 +103,7 @@ | ------------------ | ------ | ------------------------------------------------------------------------------------------------------------- | | 意见反馈入库 | 已实现 | 用户在 Workspace/Chat 提交意见后写入 `general_feedbacks`,后台报表可查看 | | 反馈企业微信群通知 | 已实现 | 反馈入库后通过 `WECOM_FEEDBACK_BOT_WEBHOOK` 即时推送到企业微信群;未配置 webhook 时静默跳过,不影响用户提交 | +| 反馈截图附件 | 已实现 | 意见反馈支持粘贴/上传截图附件(每条最多 5 张),管理端报表可查看附图缩略图与大图预览 | ## 年度教育训练计划 diff --git a/docs/superpowers/plans/2026-10-26-feedback-image-attachment.md b/docs/superpowers/plans/2026-10-26-feedback-image-attachment.md new file mode 100644 index 00000000..4e409b76 --- /dev/null +++ b/docs/superpowers/plans/2026-10-26-feedback-image-attachment.md @@ -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':}`(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`/手写 `