feat(feedback): 提交接口支持携带图片资产并校验引用
This commit is contained in:
1 parent
b31e887b2a
commit
29315cab20
6 files changed
+244
-3
No files matched your search
@@ -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)
|
||||
|
||||
@@ -0,0 +1,186 @@
|
||||
"""通用意见反馈提交 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
|
||||
@@ -294,6 +294,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.",
|
||||
|
||||
@@ -294,6 +294,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": "ไฟล์ถูกอ้างอิงโดยธุรกิจแล้ว ไม่สามารถลบได้",
|
||||
|
||||
@@ -294,6 +294,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": "文件已被业务引用,无法删除。",
|
||||
|
||||
@@ -294,6 +294,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": "檔案已被業務引用,無法刪除。",
|
||||
|
||||
Reference in new issue
Block a user