Files
syops/docs/superpowers/plans/2026-10-26-feedback-image-attachment.md

598 lines
35 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 意见反馈截图附件 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): 补充意见反馈截图附件功能项"
```