Compare commits
41
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2e8405e2f0 | ||
|
|
b2fe9b78e2 | ||
|
|
8336ab6349 | ||
|
|
d64a49548f | ||
|
|
81eeef944f | ||
|
|
60a8b20bf9 | ||
|
|
638a46ad0d | ||
|
|
1b3b63df24 | ||
|
|
eb468d3c78 | ||
|
|
8e73031e42 | ||
|
|
4105fd92f2 | ||
|
|
dd3a671a3d | ||
|
|
ee2b7cdb7e | ||
|
|
26f25d88c0 | ||
|
|
90166068ee | ||
|
|
bf44a5a70e | ||
|
|
be49b44004 | ||
|
|
d4c30b5825 | ||
|
|
836ddea84d | ||
|
|
34ad40778b | ||
|
|
e8ad4cc743 | ||
|
|
37b743d5d3 | ||
|
|
ade440d004 | ||
|
|
3f025fbb9b | ||
|
|
ed18907e95 | ||
|
|
a91f26f753 | ||
|
|
b64ed9b792 | ||
|
|
6eb4c76beb | ||
|
|
29315cab20 | ||
|
|
b31e887b2a | ||
|
|
d094d8eb83 | ||
|
|
9dd7184aa7 | ||
|
|
ec47e012a7 | ||
|
|
63a86f8944 | ||
|
|
0c27b81654 | ||
|
|
ace836c1af | ||
|
|
2cee02bec1 | ||
|
|
194a51bc2d | ||
|
|
396f17a15a | ||
|
|
f7361905b7 | ||
|
|
48fe19ed71 |
No files matched your search
@@ -101,6 +101,10 @@ backend/data/freight_rpa/
|
||||
backend/data/shipping_notice/
|
||||
backend/data/logs/
|
||||
backend/data/logs/*.log
|
||||
backend/data/logs/*.log
|
||||
# ERP HRAO 部门导入的本地数据(CSV 导出与真实公司映射不入库,模板 *.example.json 保留)
|
||||
backend/scripts/data/*.csv
|
||||
backend/scripts/data/hrao_company_map.json
|
||||
|
||||
# Engramory live memory store (plain text, machine-local)
|
||||
/.engramory-memory/
|
||||
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
backend/app/api/admin/departments.py
|
||||
|
||||
用途:管理后台部门 CRUD API(薄路由层)。
|
||||
用途:管理后台部门 CRUD API(薄路由层,树形结构)。
|
||||
依赖:admin.blueprint、services/admin/department_service。
|
||||
逻辑:/departments* 路由。
|
||||
逻辑:/departments 平铺列表(兼容旧消费方)、/departments/tree 树、成员名单(支持含下级)。
|
||||
"""
|
||||
from flask import jsonify, request
|
||||
|
||||
@@ -15,10 +15,17 @@ from app.services.admin import department_service
|
||||
@admin_bp.route('/departments', methods=['GET'])
|
||||
@require_admin
|
||||
def list_departments():
|
||||
"""返回全部部门列表。"""
|
||||
"""返回全部部门平铺列表(旧消费方兼容:部门下拉等)。"""
|
||||
return jsonify(department_service.list_departments())
|
||||
|
||||
|
||||
@admin_bp.route('/departments/tree', methods=['GET'])
|
||||
@require_admin
|
||||
def department_tree():
|
||||
"""返回完整部门树(children 嵌套,成员数含下级递归汇总)。"""
|
||||
return jsonify(department_service.list_department_tree())
|
||||
|
||||
|
||||
@admin_bp.route('/departments', methods=['POST'])
|
||||
@require_admin
|
||||
def create_department():
|
||||
@@ -31,8 +38,15 @@ def create_department():
|
||||
@admin_bp.route('/departments/<int:id>/members', methods=['GET'])
|
||||
@require_admin
|
||||
def list_department_members(id: int):
|
||||
"""返回部门员工数量与名单。"""
|
||||
return jsonify(department_service.list_department_members(id))
|
||||
"""部门员工分页名单(OA 组织面板口径):include_descendants=1 含下级,keyword 搜姓名/工号/邮箱/手机。"""
|
||||
include_descendants = request.args.get('include_descendants', '') in ('1', 'true')
|
||||
return jsonify(department_service.list_department_members(
|
||||
id,
|
||||
include_descendants,
|
||||
keyword=request.args.get('keyword', ''),
|
||||
page=request.args.get('page', 1, type=int),
|
||||
page_size=request.args.get('page_size', 20, type=int),
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/departments/<int:id>', methods=['PUT'])
|
||||
|
||||
@@ -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
|
||||
@@ -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)
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -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)
|
||||
@@ -1,27 +1,40 @@
|
||||
"""
|
||||
backend/app/models/department.py
|
||||
|
||||
用途:部门组织模型。
|
||||
用途:部门组织模型(parent_id 邻接表树形结构,对应 OA 组织架构)。
|
||||
依赖:models.base.Base。
|
||||
逻辑:parent_id 自关联构成部门树;sort_order 为同级排序(对应 ERP HRAO hrao09 阶层序号),
|
||||
is_hidden 对应 hrao08「在组织框架图中显示否」。树的组装与校验在 services/admin/department_service。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy import String, Text
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
from sqlalchemy import Boolean, ForeignKey, String, Text
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
class Department(Base):
|
||||
"""部门表:存储公司部门列表。"""
|
||||
"""部门表:存储公司部门树(parent_id 邻接表)。"""
|
||||
|
||||
__tablename__ = 'departments'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
name: Mapped[str] = mapped_column(String(100), unique=True)
|
||||
# 树形结构下 name 仅要求「同一上级下不重名」(由 department_service 校验),不再全局唯一,
|
||||
# 以支持多公司存在同名部门(如各公司均有「管理部」)。
|
||||
name: Mapped[str] = mapped_column(String(100))
|
||||
code: Mapped[Optional[str]] = mapped_column(String(50), unique=True)
|
||||
company: Mapped[Optional[str]] = mapped_column(String(100))
|
||||
description: Mapped[Optional[str]] = mapped_column(Text)
|
||||
# 上级部门主键;None 表示顶级部门(树顶公司层由前端按 company 字段虚拟分组,不入库)
|
||||
parent_id: Mapped[Optional[int]] = mapped_column(ForeignKey('departments.id'), nullable=True)
|
||||
# 同级排序号(升序),对应 ERP hrao09 部门阶层序号
|
||||
sort_order: Mapped[int] = mapped_column(default=0, server_default='0', nullable=False)
|
||||
# 是否在组织树中隐藏(对应 ERP hrao08「在组织框架图中显示否」;管理端仍可见并打标)
|
||||
is_hidden: Mapped[bool] = mapped_column(Boolean, default=False, server_default='false', nullable=False)
|
||||
|
||||
# 上级部门;children 由 backref 提供,供 service 组装树
|
||||
parent: Mapped[Optional['Department']] = relationship(remote_side=[id], backref='children')
|
||||
@@ -1,59 +1,206 @@
|
||||
"""
|
||||
backend/app/services/admin/department_service.py
|
||||
|
||||
用途:管理端部门 CRUD 业务编排。
|
||||
依赖:models.Department、app.core.errors。
|
||||
逻辑:由 api/admin/departments.py 调用。
|
||||
用途:管理端部门树 CRUD 业务编排(parent_id 邻接表)。
|
||||
依赖:models.Department、models.User、app.core.errors。
|
||||
逻辑:api/admin/departments.py 调用;成员归属沿用 users.department 文本按部门名关联;
|
||||
树顶公司层不入库,由前端按 company 字段虚拟分组。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
from collections import defaultdict
|
||||
from typing import Any, Optional
|
||||
|
||||
from sqlalchemy import func
|
||||
|
||||
from app import db
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.models import Department, User
|
||||
|
||||
# 业务错误码:与前端 locales/*/errors.json 的 codes 段一一对应
|
||||
ERR_NAME_REQUIRED = 'DEPT.NAME_REQUIRED'
|
||||
ERR_PARENT_INVALID = 'DEPT.PARENT_INVALID'
|
||||
ERR_NAME_EXISTS = 'DEPT.NAME_EXISTS'
|
||||
ERR_CODE_EXISTS = 'DEPT.CODE_EXISTS'
|
||||
ERR_CYCLE_FORBIDDEN = 'DEPT.CYCLE_FORBIDDEN'
|
||||
ERR_HAS_CHILDREN = 'DEPT.HAS_CHILDREN'
|
||||
ERR_HAS_MEMBERS = 'DEPT.HAS_MEMBERS'
|
||||
|
||||
|
||||
def serialize_department(dept: Department) -> dict:
|
||||
"""部门 ORM → API dict。"""
|
||||
"""部门 ORM → API dict(平铺行,供部门下拉等旧消费方兼容)。"""
|
||||
return {
|
||||
'id': dept.id,
|
||||
'name': dept.name,
|
||||
'code': dept.code,
|
||||
'company': dept.company,
|
||||
'description': dept.description,
|
||||
'parent_id': dept.parent_id,
|
||||
'sort_order': int(dept.sort_order or 0),
|
||||
'is_hidden': bool(dept.is_hidden),
|
||||
}
|
||||
|
||||
|
||||
def list_departments() -> list[dict]:
|
||||
"""返回全部部门(按 name 升序)。"""
|
||||
rows = (
|
||||
db.session.query(Department, func.count(User.id).label('member_count'))
|
||||
.outerjoin(User, User.department == Department.name)
|
||||
.group_by(Department.id)
|
||||
.order_by(Department.name.asc())
|
||||
.all()
|
||||
)
|
||||
return [{**serialize_department(dept), 'member_count': int(member_count or 0)} for dept, member_count in rows]
|
||||
|
||||
|
||||
def list_department_members(dept_id: int) -> dict:
|
||||
def _member_count_by_name() -> dict[str, int]:
|
||||
"""
|
||||
查询指定部门的员工名单。
|
||||
全员按部门名聚合计数。
|
||||
核心逻辑:users.department 为文本字段,一次 GROUP BY 供整棵树复用,避免逐节点查库。
|
||||
"""
|
||||
rows = db.session.query(User.department, func.count(User.id)).group_by(User.department).all()
|
||||
return {name: int(cnt) for name, cnt in rows if name}
|
||||
|
||||
[STEP 1] 通过部门主键读取部门名称。
|
||||
[STEP 2] 复用现有 users.department 文本关联查询成员。
|
||||
[STEP 3] 返回人数与脱敏后的管理端成员资料。
|
||||
|
||||
def _sibling_sort_key(node: dict) -> tuple:
|
||||
"""同级排序:sort_order 升序 → 编码 → 名称(编码可能为空,排最后)。"""
|
||||
return (node['sort_order'], node['code'] or '', node['name'])
|
||||
|
||||
|
||||
def list_departments() -> list[dict]:
|
||||
"""平铺部门列表(保持旧接口兼容),按公司 → 同级排序号 → 名称排序。"""
|
||||
depts = db.session.query(Department).all()
|
||||
counts = _member_count_by_name()
|
||||
depts.sort(key=lambda d: (d.company or '', d.sort_order or 0, d.code or '', d.name))
|
||||
return [{**serialize_department(d), 'member_count': counts.get(d.name, 0)} for d in depts]
|
||||
|
||||
|
||||
def list_department_tree() -> list[dict]:
|
||||
"""
|
||||
返回完整部门树(children 嵌套,成员数含下级递归汇总)。
|
||||
|
||||
[STEP 1] 一次取全表部门 + 一次按部门名聚合人数。
|
||||
[STEP 2] 按 parent_id 挂 children;父缺失或成环的脏数据按顶级处理(防御)。
|
||||
[STEP 3] 后序遍历汇总 total_member_count(本部门 + 全部下级)。
|
||||
[STEP 4] 同级按 sort_order → 编码 → 名称排序后输出根节点数组。
|
||||
"""
|
||||
depts = db.session.query(Department).all()
|
||||
counts = _member_count_by_name()
|
||||
dept_by_id = {d.id: d for d in depts}
|
||||
nodes = {
|
||||
d.id: {
|
||||
**serialize_department(d),
|
||||
'member_count': counts.get(d.name, 0),
|
||||
'total_member_count': counts.get(d.name, 0),
|
||||
'children': [],
|
||||
}
|
||||
for d in depts
|
||||
}
|
||||
|
||||
def _is_orphan(d: Department) -> bool:
|
||||
"""父链断裂或成环时按顶级处理,避免历史脏数据导致死循环。"""
|
||||
seen: set[int] = set()
|
||||
cur = d
|
||||
while cur.parent_id:
|
||||
if cur.parent_id not in dept_by_id or cur.parent_id in seen:
|
||||
return True
|
||||
seen.add(cur.parent_id)
|
||||
cur = dept_by_id[cur.parent_id]
|
||||
return False
|
||||
|
||||
roots: list[dict] = []
|
||||
for d in depts:
|
||||
node = nodes[d.id]
|
||||
parent_node = nodes.get(d.parent_id) if d.parent_id else None
|
||||
if parent_node is not None and not _is_orphan(d):
|
||||
parent_node['children'].append(node)
|
||||
else:
|
||||
roots.append(node)
|
||||
|
||||
def _summarize(node: dict) -> int:
|
||||
"""后序汇总:total_member_count = 本部门 + 直接成员数之和(树已去环,可安全递归)。"""
|
||||
total = node['member_count']
|
||||
for child in node['children']:
|
||||
total += _summarize(child)
|
||||
node['total_member_count'] = total
|
||||
return total
|
||||
|
||||
def _sort_level(level: list[dict]) -> None:
|
||||
level.sort(key=_sibling_sort_key)
|
||||
for n in level:
|
||||
_sort_level(n['children'])
|
||||
|
||||
_sort_level(roots)
|
||||
for r in roots:
|
||||
_summarize(r)
|
||||
return roots
|
||||
|
||||
|
||||
def _subtree_departments(root: Department) -> list[Department]:
|
||||
"""收集 root 的全部下级部门(不含 root 自身;BFS,脏数据由 parent_id 存在性保证收敛)。"""
|
||||
depts = db.session.query(Department).all()
|
||||
by_parent: dict[Optional[int], list[Department]] = defaultdict(list)
|
||||
for d in depts:
|
||||
by_parent[d.parent_id].append(d)
|
||||
out: list[Department] = []
|
||||
stack = [root.id]
|
||||
while stack:
|
||||
current = stack.pop()
|
||||
for child in by_parent.get(current, []):
|
||||
out.append(child)
|
||||
stack.append(child.id)
|
||||
return out
|
||||
|
||||
|
||||
def list_department_members(
|
||||
dept_id: int,
|
||||
include_descendants: bool = False,
|
||||
keyword: str = '',
|
||||
page: int = 1,
|
||||
page_size: int = 20,
|
||||
) -> dict:
|
||||
"""
|
||||
分页查询部门员工名单(OA 组织结构右侧面板口径)。
|
||||
|
||||
[STEP 1] 读取部门;include_descendants=True 时递归收集子树内全部部门名。
|
||||
[STEP 2] 按 users.department 文本 in 部门名集合过滤,keyword 模糊匹配
|
||||
姓名/用户名/工号/邮箱/手机号。
|
||||
[STEP 3] 返回 total 与当前页成员资料(含成员所属部门名,供含下级视图区分)。
|
||||
|
||||
Args:
|
||||
dept_id: 部门主键。
|
||||
include_descendants: 是否包含全部下级部门的成员(默认 False)。
|
||||
keyword: 搜索关键词(姓名/工号/邮箱/手机号/用户名 模糊匹配)。
|
||||
page: 页码,从 1 起;非正数按 1 处理。
|
||||
page_size: 每页条数,钳制在 1..100。
|
||||
Returns:
|
||||
{ department, total, page, page_size, members }。
|
||||
Raises:
|
||||
NotFoundError: 部门不存在。
|
||||
"""
|
||||
dept = db.session.get(Department, dept_id)
|
||||
if not dept:
|
||||
raise NotFoundError('Not found')
|
||||
users = db.session.query(User).filter(User.department == dept.name).order_by(User.real_name.asc(), User.username.asc()).all()
|
||||
raise NotFoundError('Department not found')
|
||||
if include_descendants:
|
||||
dept_names = [dept.name] + [d.name for d in _subtree_departments(dept)]
|
||||
else:
|
||||
dept_names = [dept.name]
|
||||
|
||||
query = db.session.query(User).filter(User.department.in_(dept_names))
|
||||
kw = (keyword or '').strip()
|
||||
if kw:
|
||||
like = f"%{kw}%"
|
||||
query = query.filter(
|
||||
db.or_(
|
||||
User.real_name.ilike(like),
|
||||
User.username.ilike(like),
|
||||
User.employee_id.ilike(like),
|
||||
User.email.ilike(like),
|
||||
User.phone_number.ilike(like),
|
||||
)
|
||||
)
|
||||
total = query.count()
|
||||
page = max(int(page or 1), 1)
|
||||
page_size = min(max(int(page_size or 20), 1), 100)
|
||||
users = (
|
||||
query.order_by(User.real_name.asc(), User.username.asc())
|
||||
.offset((page - 1) * page_size)
|
||||
.limit(page_size)
|
||||
.all()
|
||||
)
|
||||
return {
|
||||
'department': serialize_department(dept),
|
||||
'count': len(users),
|
||||
'total': total,
|
||||
'page': page,
|
||||
'page_size': page_size,
|
||||
'members': [
|
||||
{
|
||||
'id': user.id,
|
||||
@@ -61,6 +208,8 @@ def list_department_members(dept_id: int) -> dict:
|
||||
'real_name': user.real_name,
|
||||
'employee_id': user.employee_id,
|
||||
'email': user.email,
|
||||
'phone_number': user.phone_number,
|
||||
'department': user.department,
|
||||
'status': user.status,
|
||||
}
|
||||
for user in users
|
||||
@@ -68,25 +217,104 @@ def list_department_members(dept_id: int) -> dict:
|
||||
}
|
||||
|
||||
|
||||
def _validate_parent(parent_id: Any) -> Optional[Department]:
|
||||
"""校验上级部门存在性;None/空表示顶级。返回上级 ORM 或 None。"""
|
||||
if parent_id in (None, ''):
|
||||
return None
|
||||
parent = db.session.get(Department, int(parent_id))
|
||||
if not parent:
|
||||
raise ValidationError('Parent department not found', code=ERR_PARENT_INVALID)
|
||||
return parent
|
||||
|
||||
|
||||
def _validate_parent_change(dept: Department, new_parent_id: Any) -> Optional[Department]:
|
||||
"""
|
||||
校验修改上级的合法性:上级必须存在,且不能是自己或自己的子孙(防成环)。
|
||||
[STEP 1] 沿新上级逐层向上走。
|
||||
[STEP 2] 途中遇到本部门 id 即说明会把子树挂到自己下面,抛 CYCLE_FORBIDDEN。
|
||||
"""
|
||||
parent = _validate_parent(new_parent_id)
|
||||
if parent is None:
|
||||
return None
|
||||
if parent.id == dept.id:
|
||||
raise ValidationError('Parent cannot be itself or its descendant', code=ERR_CYCLE_FORBIDDEN)
|
||||
seen = {dept.id}
|
||||
cur_id: Optional[int] = parent.parent_id
|
||||
while cur_id:
|
||||
if cur_id in seen:
|
||||
raise ValidationError('Parent cannot be itself or its descendant', code=ERR_CYCLE_FORBIDDEN)
|
||||
seen.add(cur_id)
|
||||
cursor = db.session.get(Department, cur_id)
|
||||
if not cursor:
|
||||
break
|
||||
cur_id = cursor.parent_id
|
||||
return parent
|
||||
|
||||
|
||||
def _validate_sibling_name(
|
||||
name: str,
|
||||
parent_id: Optional[int],
|
||||
company: Optional[str] = None,
|
||||
exclude_id: Optional[int] = None,
|
||||
) -> None:
|
||||
"""
|
||||
同级查重:同一上级下 name 唯一(树形下允许不同分支同名)。
|
||||
顶级部门(parent_id 为空)按 company 分桶查重——树顶公司层为虚拟分组,
|
||||
两家公司的顶级部门允许同名(如各公司均有「管理部」)。
|
||||
"""
|
||||
query = db.session.query(Department).filter(Department.name == name)
|
||||
if parent_id:
|
||||
query = query.filter(Department.parent_id == parent_id)
|
||||
else:
|
||||
query = query.filter(Department.parent_id.is_(None))
|
||||
query = query.filter(Department.company == company) if company else query.filter(Department.company.is_(None))
|
||||
if exclude_id:
|
||||
query = query.filter(Department.id != exclude_id)
|
||||
if query.first():
|
||||
raise ValidationError('Sibling department name exists', code=ERR_NAME_EXISTS)
|
||||
|
||||
|
||||
def _clean_str(value: Any) -> str:
|
||||
return (value or '').strip() if isinstance(value, str) else ''
|
||||
|
||||
|
||||
def _clean_int(value: Any) -> int:
|
||||
try:
|
||||
return int(value)
|
||||
except (TypeError, ValueError):
|
||||
return 0
|
||||
|
||||
|
||||
def create_department(data: dict[str, Any]) -> dict:
|
||||
"""
|
||||
创建部门。
|
||||
|
||||
[STEP 1] 校验名称必填、上级存在、同级不重名、编码全局唯一。
|
||||
[STEP 2] 公司未填时继承上级部门 company(树顶公司分组依赖该字段)。
|
||||
|
||||
Returns:
|
||||
{ id, name }。
|
||||
Raises:
|
||||
ValidationError: name 缺失或 name/code 重复。
|
||||
ValidationError: NAME_REQUIRED / PARENT_INVALID / NAME_EXISTS / CODE_EXISTS。
|
||||
"""
|
||||
if not data.get('name'):
|
||||
raise ValidationError('Name is required')
|
||||
if db.session.query(Department).filter_by(name=data['name']).first():
|
||||
raise ValidationError('Name exists')
|
||||
if data.get('code') and db.session.query(Department).filter_by(code=data['code']).first():
|
||||
raise ValidationError('Code exists')
|
||||
name = _clean_str(data.get('name'))
|
||||
if not name:
|
||||
raise ValidationError('Department name is required', code=ERR_NAME_REQUIRED)
|
||||
parent_id = data.get('parent_id')
|
||||
parent = _validate_parent(parent_id)
|
||||
company = _clean_str(data.get('company')) or (parent.company if parent else None)
|
||||
_validate_sibling_name(name, parent.id if parent else None, company=company)
|
||||
code = _clean_str(data.get('code')) or None
|
||||
if code and db.session.query(Department).filter_by(code=code).first():
|
||||
raise ValidationError('Department code exists', code=ERR_CODE_EXISTS)
|
||||
dept = Department(
|
||||
name=data['name'],
|
||||
code=data.get('code'),
|
||||
company=data.get('company'),
|
||||
description=data.get('description'),
|
||||
name=name,
|
||||
code=code,
|
||||
company=company,
|
||||
description=_clean_str(data.get('description')) or None,
|
||||
parent_id=parent.id if parent else None,
|
||||
sort_order=_clean_int(data.get('sort_order')),
|
||||
is_hidden=bool(data.get('is_hidden')),
|
||||
)
|
||||
db.session.add(dept)
|
||||
db.session.commit()
|
||||
@@ -95,34 +323,64 @@ def create_department(data: dict[str, Any]) -> dict:
|
||||
|
||||
def update_department(dept_id: int, data: dict[str, Any]) -> None:
|
||||
"""
|
||||
更新部门字段。
|
||||
更新部门字段(含上级转移、同级排序、隐藏标记)。
|
||||
|
||||
[STEP 1] 名称变更时按「变更后的上级」做同级查重。
|
||||
[STEP 2] 上级变更时校验存在性并防成环。
|
||||
[STEP 3] 编码变更时全局唯一校验。
|
||||
|
||||
Raises:
|
||||
NotFoundError: 部门不存在。
|
||||
ValidationError: name/code 与其它记录冲突。
|
||||
ValidationError: NAME_EXISTS / PARENT_INVALID / CYCLE_FORBIDDEN / CODE_EXISTS。
|
||||
"""
|
||||
dept = db.session.get(Department, dept_id)
|
||||
if not dept:
|
||||
raise NotFoundError('Not found')
|
||||
if 'name' in data:
|
||||
if db.session.query(Department).filter(Department.name == data['name'], Department.id != dept_id).first():
|
||||
raise ValidationError('Name exists')
|
||||
dept.name = data['name']
|
||||
if 'code' in data:
|
||||
if data['code'] and db.session.query(Department).filter(
|
||||
Department.code == data['code'], Department.id != dept_id
|
||||
).first():
|
||||
raise ValidationError('Code exists')
|
||||
dept.code = data['code']
|
||||
raise NotFoundError('Department not found')
|
||||
|
||||
if 'parent_id' in data:
|
||||
parent = _validate_parent_change(dept, data['parent_id'])
|
||||
dept.parent_id = parent.id if parent else None
|
||||
|
||||
if 'company' in data:
|
||||
dept.company = data['company']
|
||||
dept.company = _clean_str(data.get('company')) or None
|
||||
|
||||
if 'name' in data:
|
||||
name = _clean_str(data.get('name'))
|
||||
if not name:
|
||||
raise ValidationError('Department name is required', code=ERR_NAME_REQUIRED)
|
||||
_validate_sibling_name(name, dept.parent_id, company=dept.company, exclude_id=dept_id)
|
||||
dept.name = name
|
||||
|
||||
if 'code' in data:
|
||||
code = _clean_str(data.get('code')) or None
|
||||
if code and db.session.query(Department).filter(
|
||||
Department.code == code, Department.id != dept_id
|
||||
).first():
|
||||
raise ValidationError('Department code exists', code=ERR_CODE_EXISTS)
|
||||
dept.code = code
|
||||
|
||||
if 'description' in data:
|
||||
dept.description = data['description']
|
||||
dept.description = _clean_str(data.get('description')) or None
|
||||
if 'sort_order' in data:
|
||||
dept.sort_order = _clean_int(data.get('sort_order'))
|
||||
if 'is_hidden' in data:
|
||||
dept.is_hidden = bool(data.get('is_hidden'))
|
||||
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def delete_department(dept_id: int) -> None:
|
||||
"""删除部门(不存在时静默成功)。"""
|
||||
"""
|
||||
删除部门。
|
||||
Raises:
|
||||
ConflictError: 存在下级部门(HAS_CHILDREN)或名下仍有员工(HAS_MEMBERS)时禁止删除。
|
||||
"""
|
||||
dept = db.session.get(Department, dept_id)
|
||||
if dept:
|
||||
db.session.delete(dept)
|
||||
db.session.commit()
|
||||
if not dept:
|
||||
return
|
||||
if db.session.query(Department).filter(Department.parent_id == dept_id).first():
|
||||
raise ConflictError('Department has child departments', code=ERR_HAS_CHILDREN)
|
||||
if db.session.query(User).filter(User.department == dept.name).first():
|
||||
raise ConflictError('Department still has members', code=ERR_HAS_MEMBERS)
|
||||
db.session.delete(dept)
|
||||
db.session.commit()
|
||||
@@ -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)
|
||||
|
||||
@@ -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,37 @@
|
||||
"""merge migration heads: 合并「用户多角色/意见反馈附图」与「部门树」两条迁移头
|
||||
|
||||
用途:c375467a21f9 与 eff84b4f6171 两条并行迁移链各自成头,导致
|
||||
``flask db upgrade`` 报 Multiple head revisions(见 scripts/check_migration_heads.py)。
|
||||
本迁移仅归并两条链,无任何表结构变更,upgrade/downgrade 均为空操作。
|
||||
|
||||
依赖关系:down_revision 同时挂载两条待归并的迁移头
|
||||
- c375467a21f9(合并用户多角色与意见反馈附图两条 alembic 头)
|
||||
- eff84b4f6171(合并部门树与最新 dev 迁移头)
|
||||
|
||||
逻辑关系:作为迁移图的新唯一 head,位于两条链收敛点之后,
|
||||
后续新迁移应以本 revision 为 down_revision。
|
||||
|
||||
Revision ID: d143df04ab5a
|
||||
Revises: c375467a21f9, eff84b4f6171
|
||||
Create Date: 2026-10-30
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'd143df04ab5a'
|
||||
down_revision = ('c375467a21f9', 'eff84b4f6171')
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
"""纯 merge 迁移:仅收敛迁移图,无结构变更。"""
|
||||
pass
|
||||
|
||||
|
||||
def downgrade():
|
||||
"""拆开 merge 点即回到原两条并行头,无需回滚任何结构。"""
|
||||
pass
|
||||
@@ -0,0 +1,100 @@
|
||||
"""Add department tree columns
|
||||
|
||||
Revision ID: dp1a2b3c4d5e6
|
||||
Revises: 9e5045511198
|
||||
Create Date: 2026-10-08 10:00:00.000000
|
||||
|
||||
用途:departments 表升级为树形结构(parent_id 邻接表 + 同级排序 + 隐藏标记),
|
||||
并放开 name 全局唯一约束(多公司允许同名部门,改由 service 层做同级查重)。
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'dp1a2b3c4d5e6'
|
||||
down_revision = '9e5045511198'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
conn = op.get_bind()
|
||||
insp = sa.inspect(conn)
|
||||
tables = set(insp.get_table_names())
|
||||
|
||||
if 'departments' not in tables:
|
||||
# 防御:空库直接按新结构建表
|
||||
op.create_table(
|
||||
'departments',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('name', sa.String(length=100), nullable=False),
|
||||
sa.Column('code', sa.String(length=50), nullable=True),
|
||||
sa.Column('company', sa.String(length=100), nullable=True),
|
||||
sa.Column('description', sa.Text(), nullable=True),
|
||||
sa.Column('parent_id', sa.Integer(), nullable=True),
|
||||
sa.Column('sort_order', sa.Integer(), nullable=False, server_default='0'),
|
||||
sa.Column('is_hidden', sa.Boolean(), nullable=False, server_default=sa.false()),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
sa.UniqueConstraint('code'),
|
||||
sa.ForeignKeyConstraint(
|
||||
['parent_id'], ['departments.id'], name='fk_departments_parent_id_departments'
|
||||
),
|
||||
)
|
||||
return
|
||||
|
||||
cols = {c['name'] for c in insp.get_columns('departments')}
|
||||
with op.batch_alter_table('departments', schema=None) as batch_op:
|
||||
if 'parent_id' not in cols:
|
||||
batch_op.add_column(sa.Column('parent_id', sa.Integer(), nullable=True))
|
||||
if 'sort_order' not in cols:
|
||||
batch_op.add_column(sa.Column('sort_order', sa.Integer(), nullable=False, server_default='0'))
|
||||
if 'is_hidden' not in cols:
|
||||
batch_op.add_column(sa.Column('is_hidden', sa.Boolean(), nullable=False, server_default=sa.false()))
|
||||
|
||||
# 重新内省后再补自关联外键(列可能由上一步刚添加)
|
||||
insp2 = sa.inspect(conn)
|
||||
fks = insp2.get_foreign_keys('departments')
|
||||
has_parent_fk = any(
|
||||
'parent_id' in (fk.get('constrained_columns') or []) for fk in fks
|
||||
)
|
||||
if not has_parent_fk:
|
||||
op.create_foreign_key(
|
||||
'fk_departments_parent_id_departments', 'departments', 'departments',
|
||||
['parent_id'], ['id'],
|
||||
)
|
||||
|
||||
# 放开 name 全局唯一:删除覆盖 name 列的 unique 约束(同名约束名在不同库不一致,按列名探测)
|
||||
name_uq_names = [
|
||||
uq['name'] for uq in insp2.get_unique_constraints('departments')
|
||||
if set(uq.get('column_names') or []) == {'name'} and uq.get('name')
|
||||
]
|
||||
if name_uq_names:
|
||||
with op.batch_alter_table('departments', schema=None) as batch_op:
|
||||
for uq_name in name_uq_names:
|
||||
batch_op.drop_constraint(uq_name, type_='unique')
|
||||
|
||||
|
||||
def downgrade():
|
||||
conn = op.get_bind()
|
||||
insp = sa.inspect(conn)
|
||||
if 'departments' not in set(insp.get_table_names()):
|
||||
return
|
||||
|
||||
cols = {c['name'] for c in insp.get_columns('departments')}
|
||||
with op.batch_alter_table('departments', schema=None) as batch_op:
|
||||
if 'is_hidden' in cols:
|
||||
batch_op.drop_column('is_hidden')
|
||||
if 'sort_order' in cols:
|
||||
batch_op.drop_column('sort_order')
|
||||
if 'parent_id' in cols:
|
||||
try:
|
||||
batch_op.drop_constraint('fk_departments_parent_id_departments', type_='foreignkey')
|
||||
except Exception:
|
||||
pass
|
||||
batch_op.drop_column('parent_id')
|
||||
# 恢复 name 全局唯一;若历史数据存在重名会失败,需先清洗数据
|
||||
try:
|
||||
batch_op.create_unique_constraint('uq_departments_name', ['name'])
|
||||
except Exception:
|
||||
pass
|
||||
@@ -0,0 +1,24 @@
|
||||
"""merge department tree and latest dev migration heads
|
||||
|
||||
Revision ID: eff84b4f6171
|
||||
Revises: fa1d22f99de9, pr0a1b2c3d4e5
|
||||
Create Date: 2026-10-29 17:06:07.732022
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'eff84b4f6171'
|
||||
down_revision = ('fa1d22f99de9', 'pr0a1b2c3d4e5')
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
pass
|
||||
|
||||
|
||||
def downgrade():
|
||||
pass
|
||||
@@ -0,0 +1,24 @@
|
||||
"""merge department tree and dev migration heads
|
||||
|
||||
Revision ID: fa1d22f99de9
|
||||
Revises: dp1a2b3c4d5e6, eah8c9d0e1f2
|
||||
Create Date: 2026-10-22 13:19:23.491330
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'fa1d22f99de9'
|
||||
down_revision = ('dp1a2b3c4d5e6', 'eah8c9d0e1f2')
|
||||
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,11 @@
|
||||
{
|
||||
"_comment": "hrao00 -> 公司中文名。来源 ERP dc.HRAA_FILE(hraa01=公司编号,hraa02=公司名称)。0000 集团公司无部门,保留映射以备后续。",
|
||||
"0000": "集团公司",
|
||||
"0001": "电子",
|
||||
"0002": "科技",
|
||||
"0003": "和信",
|
||||
"0004": "泰国合欣",
|
||||
"0005": "台湾尊场",
|
||||
"0006": "无锡和宏智",
|
||||
"0007": "上海数智"
|
||||
}
|
||||
@@ -0,0 +1,358 @@
|
||||
"""Import ERP HRAO_FILE departments into the local department tree.
|
||||
|
||||
Purpose: one-shot import of the Tiptop department master (ERP `dc.HRAO_FILE`) exported as
|
||||
CSV from DBeaver into the local `departments` tree, upserting by department code (hrao01).
|
||||
Dependencies: Flask app context, SQLAlchemy models, csv/json stdlib (no Oracle driver).
|
||||
Flow: dry-run is the default and only prints a validation report; pass `--apply` to write.
|
||||
hrao06 parent codes resolve to hrao01 after all rows are upserted; dangling parents and
|
||||
cycles fall back to top-level with a report. Local rows whose code is absent from the ERP
|
||||
file are kept untouched (per the agreed merge policy). `users.department` links by name
|
||||
text, so renames are reported for manual re-linking instead of being rewritten here.
|
||||
|
||||
Usage (from backend/):
|
||||
python scripts/import_departments_from_hrao.py --file scripts/data/hrao_departments.csv
|
||||
python scripts/import_departments_from_hrao.py --file ... --apply
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
from collections import Counter
|
||||
from pathlib import Path
|
||||
from typing import Any, Optional
|
||||
|
||||
BACKEND_ROOT = Path(__file__).resolve().parents[1]
|
||||
if str(BACKEND_ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(BACKEND_ROOT))
|
||||
|
||||
from app import create_app
|
||||
from app.extensions import db
|
||||
from app.models import Department, User
|
||||
|
||||
DEFAULT_CSV = Path("scripts/data/hrao_departments.csv")
|
||||
DEFAULT_COMPANY_MAP = Path("scripts/data/hrao_company_map.json")
|
||||
HIDDEN_MODES = ("ignore", "n_is_hidden", "not_y_is_hidden")
|
||||
|
||||
|
||||
def _clean(value: Any) -> str:
|
||||
"""Trim a CSV cell to a normalized string ('' for None)."""
|
||||
return str(value or "").strip()
|
||||
|
||||
|
||||
def _read_csv(path: Path) -> list[dict[str, str]]:
|
||||
"""Read the DBeaver CSV export; headers are normalized to lowercase (utf-8 with BOM tolerated).
|
||||
|
||||
Args:
|
||||
path: CSV file exported from `SELECT hrao00, hrao01, hrao02, hrao03, hrao06, hrao09, ... FROM dc.HRAO_FILE`.
|
||||
Returns:
|
||||
List of row dicts keyed by lowercase column names (hrao00 ...).
|
||||
Raises:
|
||||
SystemExit: file missing or no recognizable hrao01 header.
|
||||
"""
|
||||
if not path.exists():
|
||||
raise SystemExit(f"CSV not found: {path}\n先在 DBeaver 导出 HRAO 查询结果为 CSV(UTF-8),再放到该路径。")
|
||||
import csv
|
||||
|
||||
with path.open(encoding="utf-8-sig", newline="") as fh:
|
||||
reader = csv.DictReader(fh)
|
||||
rows = [
|
||||
{(k or "").strip().lower(): (v or "") for k, v in raw.items()}
|
||||
for raw in reader
|
||||
]
|
||||
if rows and not any("hrao01" in row for row in rows[:1]):
|
||||
raise SystemExit(f"CSV 首行未找到 hrao01 列头,请确认导出来自 HRAO_FILE 查询:{path}")
|
||||
return rows
|
||||
|
||||
|
||||
def _load_company_map(path: Path) -> dict[str, str]:
|
||||
"""Load hrao00 -> company display name mapping from a JSON file.
|
||||
|
||||
Raises:
|
||||
SystemExit: mapping file missing (with a template hint).
|
||||
"""
|
||||
if not path.exists():
|
||||
raise SystemExit(
|
||||
f"公司映射文件不存在:{path}\n"
|
||||
'请创建 JSON:{"0002": "苏州和信精密科技有限公司", ...}(hrao00 -> 公司中文名)。'
|
||||
)
|
||||
data = json.loads(path.read_text(encoding="utf-8"))
|
||||
return {_clean(k): _clean(v) for k, v in data.items() if _clean(k)}
|
||||
|
||||
|
||||
def _parse_hidden(hrao08: str, mode: str) -> bool:
|
||||
"""Map hrao08 (在组织框架图中显示否) to is_hidden per the chosen mode.
|
||||
|
||||
Args:
|
||||
mode: ignore(默认,全部不隐藏)| n_is_hidden(N=不显示→隐藏)| not_y_is_hidden(非 Y 即隐藏)。
|
||||
"""
|
||||
flag = _clean(hrao08).upper()
|
||||
if mode == "n_is_hidden":
|
||||
return flag == "N"
|
||||
if mode == "not_y_is_hidden":
|
||||
return flag != "Y"
|
||||
return False
|
||||
|
||||
|
||||
def _normalize_rows(
|
||||
raw_rows: list[dict[str, str]], hidden_mode: str
|
||||
) -> tuple[list[dict[str, Any]], list[str]]:
|
||||
"""Normalize CSV rows into import payloads; duplicate hrao01 keeps the first occurrence.
|
||||
|
||||
Returns:
|
||||
(rows, problems) — rows keyed by code with name/company_code/parent_code/sort_order/is_hidden.
|
||||
"""
|
||||
rows: dict[str, dict[str, Any]] = {}
|
||||
problems: list[str] = []
|
||||
for raw in raw_rows:
|
||||
code = _clean(raw.get("hrao01"))
|
||||
name = _clean(raw.get("hrao02")) or _clean(raw.get("hrao03"))
|
||||
if not code:
|
||||
problems.append(f"跳过:hrao01 为空(hrao02={_clean(raw.get('hrao02'))!r})")
|
||||
continue
|
||||
if not name:
|
||||
problems.append(f"跳过:{code} 部门名称为空(hrao02/hrao03 均空)")
|
||||
continue
|
||||
if code in rows:
|
||||
problems.append(f"跳过重复编码:{code} 第二次出现({name!r}),保留首行")
|
||||
continue
|
||||
sort_raw = _clean(raw.get("hrao09"))
|
||||
parent = _clean(raw.get("hrao06"))
|
||||
rows[code] = {
|
||||
"code": code,
|
||||
"name": name,
|
||||
"company_code": _clean(raw.get("hrao00")),
|
||||
"parent_code": parent if parent and parent != "0" else None,
|
||||
"sort_order": int(sort_raw) if sort_raw.isdigit() else 0,
|
||||
"is_hidden": _parse_hidden(raw.get("hrao08"), hidden_mode),
|
||||
}
|
||||
return list(rows.values()), problems
|
||||
|
||||
|
||||
def _resolve_parents(rows: list[dict[str, Any]]) -> tuple[dict[str, Optional[str]], list[str]]:
|
||||
"""Resolve each row's parent code; dangling/self references fall back to top-level.
|
||||
|
||||
Returns:
|
||||
(parent_by_code, problems) — parent codes or None for top-level.
|
||||
"""
|
||||
codes = {r["code"] for r in rows}
|
||||
parent_by_code: dict[str, Optional[str]] = {}
|
||||
problems: list[str] = []
|
||||
for row in rows:
|
||||
parent = row["parent_code"]
|
||||
if parent is not None and (parent not in codes or parent == row["code"]):
|
||||
problems.append(f"悬空上级:{row['code']} {row['name']} 的 hrao06={parent!r} 匹配不到 hrao01,按顶级导入")
|
||||
parent = None
|
||||
parent_by_code[row["code"]] = parent
|
||||
return parent_by_code, problems
|
||||
|
||||
|
||||
def _break_cycles(
|
||||
rows: list[dict[str, Any]], parent_by_code: dict[str, Optional[str]]
|
||||
) -> tuple[dict[str, Optional[str]], list[str]]:
|
||||
"""Rows caught in a parent cycle (e.g. A->B->A) are detached to top-level.
|
||||
|
||||
Returns:
|
||||
(parent_by_code, problems)
|
||||
"""
|
||||
problems: list[str] = []
|
||||
for row in rows:
|
||||
seen: set[str] = set()
|
||||
cursor: Optional[str] = row["code"]
|
||||
cyclic = False
|
||||
while cursor and parent_by_code.get(cursor):
|
||||
if cursor in seen:
|
||||
cyclic = True
|
||||
break
|
||||
seen.add(cursor)
|
||||
cursor = parent_by_code[cursor]
|
||||
if cyclic:
|
||||
name = next(r["name"] for r in rows if r["code"] == row["code"])
|
||||
problems.append(f"成环:{row['code']} {name} 的上级链形成环,整链按顶级导入")
|
||||
parent_by_code[row["code"]] = None
|
||||
return parent_by_code, problems
|
||||
|
||||
|
||||
def _find_name_conflicts(
|
||||
rows: list[dict[str, Any]], parent_by_code: dict[str, Optional[str]]
|
||||
) -> list[str]:
|
||||
"""Same-parent (or same-company top-level) duplicate names would fail sibling validation."""
|
||||
buckets: Counter = Counter()
|
||||
for row in rows:
|
||||
parent = parent_by_code[row["code"]]
|
||||
company = row["company_code"] if parent is None else parent
|
||||
buckets[(company, parent, row["name"])] += 1
|
||||
return [
|
||||
f"同级重名:{name!r}(公司/父={key})出现 {count} 次,需人工改名后再导入"
|
||||
for (key, _, name), count in buckets.items()
|
||||
if count > 1
|
||||
]
|
||||
|
||||
|
||||
def plan_import(
|
||||
rows: list[dict[str, Any]],
|
||||
company_map: dict[str, str],
|
||||
allow_unmapped: bool,
|
||||
) -> tuple[dict[str, Any], list[str]]:
|
||||
"""Diff ERP rows against local departments into an upsert plan.
|
||||
|
||||
Args:
|
||||
rows: normalized ERP rows.
|
||||
company_map: hrao00 -> company display name.
|
||||
allow_unmapped: when False, unmapped hrao00 aborts the plan (apply refuses).
|
||||
Returns:
|
||||
(plan, problems) — plan holds inserts/updates/kept/dangling etc. for the reporter.
|
||||
"""
|
||||
problems: list[str] = []
|
||||
unmapped = sorted({r["company_code"] for r in rows if r["company_code"] and r["company_code"] not in company_map})
|
||||
if unmapped and not allow_unmapped:
|
||||
problems.append(f"未映射的公司编码:{unmapped}(补 hrao_company_map.json 或加 --allow-unmapped)")
|
||||
|
||||
for row in rows:
|
||||
row["company"] = company_map.get(row["company_code"])
|
||||
|
||||
local_by_code = {d.code: d for d in db.session.query(Department).all()}
|
||||
inserts = [r for r in rows if r["code"] not in local_by_code]
|
||||
updates = [
|
||||
{"local": local_by_code[r["code"]], "row": r}
|
||||
for r in rows
|
||||
if r["code"] in local_by_code
|
||||
]
|
||||
kept = sorted(set(local_by_code) - {r["code"] for r in rows})
|
||||
|
||||
renames = []
|
||||
for item in updates:
|
||||
old_name = item["local"].name
|
||||
if old_name != item["row"]["name"]:
|
||||
linked = db.session.query(User).filter(User.department == old_name).count()
|
||||
renames.append((old_name, item["row"]["name"], linked))
|
||||
|
||||
plan = {
|
||||
"inserts": inserts,
|
||||
"updates": updates,
|
||||
"kept": kept,
|
||||
"renames": renames,
|
||||
"unmapped": unmapped,
|
||||
}
|
||||
return plan, problems
|
||||
|
||||
|
||||
def apply_plan(plan: dict[str, Any], parent_by_code: dict[str, Optional[str]]) -> tuple[int, int]:
|
||||
"""Execute the plan in one transaction; parents are linked after ids exist.
|
||||
|
||||
Returns:
|
||||
(created, updated) row counts.
|
||||
"""
|
||||
code_to_id = {d.code: d.id for d in db.session.query(Department).all()}
|
||||
created = updated = 0
|
||||
# [STEP 1] 先落行(parent_id 暂空),拿到主键后再统一挂父,避免插入顺序依赖
|
||||
for row in plan["inserts"]:
|
||||
dept = Department(
|
||||
name=row["name"],
|
||||
code=row["code"],
|
||||
company=row["company"],
|
||||
parent_id=None,
|
||||
sort_order=row["sort_order"],
|
||||
is_hidden=row["is_hidden"],
|
||||
)
|
||||
db.session.add(dept)
|
||||
db.session.flush()
|
||||
code_to_id[row["code"]] = dept.id
|
||||
created += 1
|
||||
# [STEP 2] 更新已存在行(按编码 upsert,保留本地多余行)
|
||||
for item in plan["updates"]:
|
||||
local, row = item["local"], item["row"]
|
||||
local.name = row["name"]
|
||||
local.company = row["company"]
|
||||
local.sort_order = row["sort_order"]
|
||||
local.is_hidden = row["is_hidden"]
|
||||
updated += 1
|
||||
# [STEP 3] 挂上级:本地已有编码或本次新插入的编码都可作为父
|
||||
for row in plan["inserts"] + [i["row"] for i in plan["updates"]]:
|
||||
parent_code = parent_by_code[row["code"]]
|
||||
if parent_code:
|
||||
db.session.get(Department, code_to_id[row["code"]]).parent_id = code_to_id.get(parent_code)
|
||||
db.session.commit()
|
||||
return created, updated
|
||||
|
||||
|
||||
def _print_report(
|
||||
rows: list[dict[str, Any]],
|
||||
plan: dict[str, Any],
|
||||
problems: list[str],
|
||||
company_map: dict[str, str],
|
||||
raw_rows: list[dict[str, str]],
|
||||
) -> None:
|
||||
"""Print the dry-run/apply report; problem lines always warn before the summary."""
|
||||
companies = Counter(r["company_code"] for r in rows)
|
||||
print("== 公司分布(hrao00 -> 行数)==")
|
||||
for code, count in sorted(companies.items()):
|
||||
print(f" {code or '(空)'} x{count} -> {company_map.get(code, '(未映射)')}")
|
||||
if plan["unmapped"]:
|
||||
print(f" ⚠ 未映射编码:{plan['unmapped']}")
|
||||
print(f"== 汇总 == ERP 行 {len(rows)};插入 {len(plan['inserts'])};更新 {len(plan['updates'])};本地保留 {len(plan['kept'])}")
|
||||
if plan["renames"]:
|
||||
print("== 更名(users.department 按名称关联,需人工重挂)==")
|
||||
for old, new, linked in plan["renames"]:
|
||||
print(f" {old!r} -> {new!r}(名下员工 {linked} 人)")
|
||||
for line in problems:
|
||||
print(f" ⚠ {line}")
|
||||
if not any("⚠" in line for line in problems) and not plan["renames"]:
|
||||
print(" (无告警)")
|
||||
# hrao 标志位分布,帮助确认 is_hidden 映射是否正确
|
||||
for col in ("hrao05", "hrao07", "hrao08"):
|
||||
dist = Counter(_clean(r.get(col)).upper() for r in raw_rows)
|
||||
print(f"== {col} 取值分布 == {dict(dist)}")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
"""Parse args, build the plan, and write only with --apply (single transaction)."""
|
||||
parser = argparse.ArgumentParser(description="Import ERP HRAO_FILE departments (CSV) into the local tree")
|
||||
parser.add_argument("--file", type=Path, default=DEFAULT_CSV, help="DBeaver 导出的 HRAO CSV 路径")
|
||||
parser.add_argument("--company-map", type=Path, default=DEFAULT_COMPANY_MAP, help="hrao00 -> 公司名 JSON")
|
||||
parser.add_argument("--hidden-mode", choices=HIDDEN_MODES, default="ignore",
|
||||
help="hrao08 -> is_hidden 映射;默认 ignore(不隐藏)")
|
||||
parser.add_argument("--allow-unmapped", action="store_true", help="允许未映射公司编码(company 置空)")
|
||||
parser.add_argument("--company", action="append", default=None,
|
||||
help="只导入指定 hrao00 的公司(可多次传入,如 --company 0003);缺省导入全部")
|
||||
parser.add_argument("--apply", action="store_true", help="真正写库;缺省仅 dry-run 预览")
|
||||
args = parser.parse_args()
|
||||
|
||||
company_map = _load_company_map(args.company_map)
|
||||
raw_rows = _read_csv(args.file)
|
||||
rows, problems = _normalize_rows(raw_rows, args.hidden_mode)
|
||||
if args.company:
|
||||
wanted = {c.strip() for c in args.company}
|
||||
missing = wanted - {r["company_code"] for r in rows}
|
||||
if missing:
|
||||
raise SystemExit(f"CSV 中不存在这些公司编码:{sorted(missing)}")
|
||||
rows = [r for r in rows if r["company_code"] in wanted]
|
||||
if args.company:
|
||||
wanted = {c.strip() for c in args.company}
|
||||
missing = wanted - {r["company_code"] for r in rows}
|
||||
if missing:
|
||||
raise SystemExit(f"CSV 中不存在这些公司编码:{sorted(missing)}")
|
||||
rows = [r for r in rows if r["company_code"] in wanted]
|
||||
parent_by_code, parent_problems = _resolve_parents(rows)
|
||||
parent_by_code, cycle_problems = _break_cycles(rows, parent_by_code)
|
||||
problems += parent_problems + cycle_problems
|
||||
problems += _find_name_conflicts(rows, parent_by_code)
|
||||
|
||||
app = create_app()
|
||||
with app.app_context():
|
||||
plan, plan_problems = plan_import(rows, company_map, args.allow_unmapped)
|
||||
problems += plan_problems
|
||||
_print_report(rows, plan, problems, company_map, raw_rows)
|
||||
fatal = [p for p in problems if "需人工" in p or "未映射的公司编码" in p]
|
||||
if args.apply and not fatal:
|
||||
created, updated = apply_plan(plan, parent_by_code)
|
||||
print(f"✅ 已写入:插入 {created},更新 {updated}(事务已提交)")
|
||||
elif args.apply:
|
||||
raise SystemExit("存在需人工处理的告警,已阻止写库;处理后重试或加对应参数。")
|
||||
else:
|
||||
print("(dry-run 未写库;确认无误后加 --apply 执行)")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -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
|
||||
@@ -1,45 +1,180 @@
|
||||
"""
|
||||
tests/services/admin/test_department_service.py
|
||||
|
||||
用途:department_service CRUD 单元测试。
|
||||
用途:department_service 部门树 CRUD、树组装、成员口径单元测试。
|
||||
覆盖:父子挂接 / 同级查重 / 编码唯一 / 防成环 / 删除保护(有下级、有员工)/ 成员数含下级汇总。
|
||||
"""
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.models import Department
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.models import Department, User
|
||||
from app.services.admin.department_service import (
|
||||
create_department,
|
||||
delete_department,
|
||||
list_department_members,
|
||||
list_department_tree,
|
||||
list_departments,
|
||||
update_department,
|
||||
)
|
||||
|
||||
|
||||
def test_department_crud(app):
|
||||
def test_department_crud_with_parent(app):
|
||||
"""断言:父子挂接进树、字段可更新、有下级禁删、无下级可删。"""
|
||||
with app.app_context():
|
||||
created = create_department({'name': 'R&D', 'code': 'RD', 'company': 'HX'})
|
||||
assert created['name'] == 'R&D'
|
||||
parent = create_department({'name': '品保部', 'code': 'QA', 'company': 'HX'})
|
||||
child = create_department({'name': '品保课', 'code': 'QA1', 'parent_id': parent['id'], 'sort_order': 2})
|
||||
assert child['name'] == '品保课'
|
||||
|
||||
items = list_departments()
|
||||
assert any(item['code'] == 'RD' for item in items)
|
||||
assert any(item['code'] == 'QA1' and item['parent_id'] == parent['id'] for item in items)
|
||||
|
||||
update_department(created['id'], {'description': 'Research'})
|
||||
dept = db.session.get(Department, created['id'])
|
||||
assert dept.description == 'Research'
|
||||
update_department(child['id'], {'sort_order': 9, 'is_hidden': True})
|
||||
dept = db.session.get(Department, child['id'])
|
||||
assert dept.sort_order == 9
|
||||
assert dept.is_hidden is True
|
||||
|
||||
delete_department(created['id'])
|
||||
assert db.session.get(Department, created['id']) is None
|
||||
# 分支测试意图:存在下级部门时删除必须被 HAS_CHILDREN 拦截
|
||||
with pytest.raises(ConflictError, match='child'):
|
||||
delete_department(parent['id'])
|
||||
delete_department(child['id'])
|
||||
delete_department(parent['id'])
|
||||
assert db.session.get(Department, parent['id']) is None
|
||||
|
||||
|
||||
def test_create_department_rejects_duplicate_name(app):
|
||||
def test_create_department_rejects_same_parent_duplicate_name(app):
|
||||
"""断言:同一上级下同名部门被拒(同级查重)。"""
|
||||
with app.app_context():
|
||||
create_department({'name': 'Sales'})
|
||||
with pytest.raises(ValidationError, match='Name exists'):
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
create_department({'name': 'Sales'})
|
||||
# 断言业务错误码而非消息文本(str(exc) 仅含 message,不含 code)
|
||||
assert exc_info.value.code == 'DEPT.NAME_EXISTS'
|
||||
|
||||
|
||||
def test_create_department_allows_same_name_under_different_parents(app):
|
||||
"""断言:不同分支(多公司)允许同名部门——name 全局唯一已放开。"""
|
||||
with app.app_context():
|
||||
root_a = create_department({'name': '和信', 'company': '和信'})
|
||||
root_b = create_department({'name': '泰国合欣', 'company': '泰国合欣'})
|
||||
create_department({'name': '管理部', 'parent_id': root_a['id']})
|
||||
create_department({'name': '管理部', 'parent_id': root_b['id']})
|
||||
tree = list_department_tree()
|
||||
assert len(tree) == 2
|
||||
assert all(len([c for c in root['children'] if c['name'] == '管理部']) == 1 for root in tree)
|
||||
|
||||
|
||||
def test_create_department_allows_same_name_root_across_companies(app):
|
||||
"""分支测试意图:两家公司的顶级部门允许同名(按 company 分桶查重),同公司顶级同名仍拒绝。"""
|
||||
with app.app_context():
|
||||
create_department({'name': '管理部', 'company': '苏州和信'})
|
||||
create_department({'name': '管理部', 'company': '泰国合欣'})
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
create_department({'name': '管理部', 'company': '苏州和信'})
|
||||
assert exc_info.value.code == 'DEPT.NAME_EXISTS'
|
||||
|
||||
|
||||
def test_create_department_inherits_company_from_parent(app):
|
||||
"""断言:未填公司时继承上级部门 company(公司虚拟分组依赖)。"""
|
||||
with app.app_context():
|
||||
root = create_department({'name': '和信', 'company': '苏州和信'})
|
||||
child = create_department({'name': '财务部', 'parent_id': root['id']})
|
||||
dept = db.session.get(Department, child['id'])
|
||||
assert dept.company == '苏州和信'
|
||||
|
||||
|
||||
def test_create_department_rejects_duplicate_code(app):
|
||||
"""断言:部门编码全局唯一。"""
|
||||
with app.app_context():
|
||||
create_department({'name': 'A', 'code': 'C1'})
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
create_department({'name': 'B', 'code': 'C1'})
|
||||
assert exc_info.value.code == 'DEPT.CODE_EXISTS'
|
||||
|
||||
|
||||
def test_update_parent_cycle_rejected(app):
|
||||
"""分支测试意图:把部门挂到自己或自己的子孙下必须被 CYCLE_FORBIDDEN 拦截。"""
|
||||
with app.app_context():
|
||||
root = create_department({'name': 'Root'})
|
||||
child = create_department({'name': 'Child', 'parent_id': root['id']})
|
||||
grand = create_department({'name': 'Grand', 'parent_id': child['id']})
|
||||
assert grand['name'] == 'Grand'
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
update_department(root['id'], {'parent_id': grand['id']})
|
||||
assert exc_info.value.code == 'DEPT.CYCLE_FORBIDDEN'
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
update_department(root['id'], {'parent_id': root['id']})
|
||||
assert exc_info.value.code == 'DEPT.CYCLE_FORBIDDEN'
|
||||
|
||||
|
||||
def test_update_department_not_found(app):
|
||||
with app.app_context():
|
||||
with pytest.raises(NotFoundError):
|
||||
update_department(99999, {'name': 'X'})
|
||||
|
||||
|
||||
def test_delete_department_with_members_rejected(app):
|
||||
"""断言:名下仍有员工(users.department 文本命中)时删除被 HAS_MEMBERS 拦截。"""
|
||||
with app.app_context():
|
||||
dept = create_department({'name': '品保部'})
|
||||
db.session.add(User(username='u1', email='u1@example.com', department='品保部', role='user', status='active'))
|
||||
db.session.commit()
|
||||
with pytest.raises(ConflictError, match='members'):
|
||||
delete_department(dept['id'])
|
||||
|
||||
|
||||
def test_member_count_tree_rollup_and_members_scope(app):
|
||||
"""断言:树节点 member_count 为直属人数、total_member_count 递归含下级;成员接口按口径过滤。"""
|
||||
with app.app_context():
|
||||
root = create_department({'name': '物料部'})
|
||||
child = create_department({'name': '仓储课', 'parent_id': root['id']})
|
||||
db.session.add_all([
|
||||
User(username='r1', email='r1@example.com', department='物料部', role='user', status='active'),
|
||||
User(username='c1', email='c1@example.com', department='仓储课', role='user', status='active'),
|
||||
User(username='c2', email='c2@example.com', department='仓储课', role='user', status='active'),
|
||||
])
|
||||
db.session.commit()
|
||||
|
||||
tree = list_department_tree()
|
||||
node = tree[0]
|
||||
assert node['member_count'] == 1
|
||||
assert node['total_member_count'] == 3
|
||||
assert node['children'][0]['total_member_count'] == 2
|
||||
|
||||
direct = list_department_members(child['id'])
|
||||
assert direct['total'] == 2
|
||||
subtree = list_department_members(root['id'], include_descendants=True)
|
||||
assert subtree['total'] == 3
|
||||
assert all(member.get('department') in ('物料部', '仓储课') for member in subtree['members'])
|
||||
|
||||
|
||||
def test_members_keyword_search_and_pagination(app):
|
||||
"""分支测试意图:成员接口按 姓名/工号/手机 模糊搜索,并按 page/page_size 分页。"""
|
||||
with app.app_context():
|
||||
dept = create_department({'name': '品保部'})
|
||||
db.session.add_all([
|
||||
User(username='u1', real_name='张一', employee_id='E001', phone_number='13800000001',
|
||||
email='u1@example.com', department='品保部', role='user', status='active'),
|
||||
User(username='u2', real_name='张二', employee_id='E002', phone_number='13800000002',
|
||||
email='u2@example.com', department='品保部', role='user', status='active'),
|
||||
User(username='u3', real_name='李三', employee_id='E003', phone_number='13800000003',
|
||||
email='u3@example.com', department='品保部', role='user', status='active'),
|
||||
])
|
||||
db.session.commit()
|
||||
|
||||
# 关键词命中工号
|
||||
by_emp = list_department_members(dept['id'], keyword='E003')
|
||||
assert by_emp['total'] == 1
|
||||
assert by_emp['members'][0]['real_name'] == '李三'
|
||||
# 关键词命中手机号
|
||||
by_phone = list_department_members(dept['id'], keyword='13800000002')
|
||||
assert by_phone['total'] == 1
|
||||
assert by_phone['members'][0]['username'] == 'u2'
|
||||
# 关键词命中姓名(同姓两人)
|
||||
by_name = list_department_members(dept['id'], keyword='张')
|
||||
assert by_name['total'] == 2
|
||||
# 分页:page_size=2 时第 2 页只剩 1 条
|
||||
paged = list_department_members(dept['id'], page=2, page_size=2)
|
||||
assert paged['total'] == 3
|
||||
assert paged['page'] == 2
|
||||
assert len(paged['members']) == 1
|
||||
@@ -0,0 +1,82 @@
|
||||
"""
|
||||
backend/tests/services/test_feedback_notify.py
|
||||
|
||||
用途:锁定企微反馈通知 markdown 组装契约——有图反馈在「反馈内容」段之前
|
||||
多一行「附图:N 张」(N>0 时),无图反馈不得出现「附图」字样,
|
||||
且其余既有行内容与顺序零改动。
|
||||
依赖:app 夹具(create_app('testing') + db.create_all,不走迁移)、
|
||||
GeneralFeedback/GeneralFeedbackImage/User/FileAsset 模型、
|
||||
app.services.feedback_notify.build_feedback_markdown。
|
||||
逻辑:build_feedback_markdown 为纯组装函数(不发网络请求),测试直接落
|
||||
User/FileAsset/GeneralFeedback/GeneralFeedbackImage 行后调用并断言文本,
|
||||
覆盖有图(2 张)与无图两条路径。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from uuid import uuid4
|
||||
|
||||
from app import db
|
||||
from app.models import FileAsset, GeneralFeedback, GeneralFeedbackImage, User
|
||||
from app.services.feedback_notify import build_feedback_markdown
|
||||
|
||||
|
||||
def _create_user(username: str) -> User:
|
||||
"""按用户名幂等落一个测试用户(GeneralFeedback.user_id 外键依赖)。"""
|
||||
user = db.session.query(User).filter_by(username=username).first()
|
||||
if not user:
|
||||
user = User(username=username, email=f"{username}@example.com", role="user", status="active")
|
||||
user.set_password("x")
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
return user
|
||||
|
||||
|
||||
def _make_asset(user_id: int) -> FileAsset:
|
||||
"""直接落一条 ready/temporary 的图片 FileAsset 行(GeneralFeedbackImage.asset_id 外键依赖)。"""
|
||||
asset = FileAsset(
|
||||
asset_no=f"FA-TEST-{uuid4().hex[:8].upper()}", owner_user_id=int(user_id),
|
||||
original_filename="screenshot.png", storage_provider="minio", storage_bucket="test",
|
||||
storage_key=f"test/{user_id}/{uuid4().hex}", content_hash="0" * 64, file_size=1024,
|
||||
mime_type="image/png", extension="png", upload_status="ready",
|
||||
lifecycle_status="temporary", reference_count=0,
|
||||
)
|
||||
db.session.add(asset)
|
||||
db.session.commit()
|
||||
return asset
|
||||
|
||||
|
||||
def _create_feedback(user: User, content: str) -> GeneralFeedback:
|
||||
"""落一条最小可用的 GeneralFeedback 行(必填字段齐全)。"""
|
||||
feedback = GeneralFeedback(
|
||||
user_id=user.id, username=user.username,
|
||||
feedback_type="问题反馈", feedback_module="知识库", content=content,
|
||||
source_page="workspace",
|
||||
)
|
||||
db.session.add(feedback)
|
||||
db.session.commit()
|
||||
return feedback
|
||||
|
||||
|
||||
def test_markdown_includes_image_count(app):
|
||||
"""有图反馈:markdown 含「附图:2 张」行;无图反馈:不含「附图」。"""
|
||||
with app.app_context():
|
||||
user = _create_user("notifyuser")
|
||||
# 有图反馈:2 条图片关联(asset_id 唯一,各自独立 FileAsset),走真实 images relationship
|
||||
fb_with_images = _create_feedback(user, "这条反馈带两张截图")
|
||||
db.session.add_all([
|
||||
GeneralFeedbackImage(feedback_id=fb_with_images.id, asset_id=_make_asset(user.id).id, sort_order=0),
|
||||
GeneralFeedbackImage(feedback_id=fb_with_images.id, asset_id=_make_asset(user.id).id, sort_order=1),
|
||||
])
|
||||
db.session.commit()
|
||||
# 无图反馈:不落任何 GeneralFeedbackImage
|
||||
fb_without_images = _create_feedback(user, "这条反馈没有截图")
|
||||
|
||||
md_with_images = build_feedback_markdown(fb_with_images, None)
|
||||
md_without_images = build_feedback_markdown(fb_without_images, None)
|
||||
|
||||
# 有图:附图行存在,且必须位于「反馈内容」块之前
|
||||
assert "附图:2 张" in md_with_images
|
||||
assert md_with_images.index("附图:2 张") < md_with_images.index("**反馈内容:**")
|
||||
# 无图:不得出现「附图」字样
|
||||
assert "附图" not in md_without_images
|
||||
@@ -103,6 +103,7 @@
|
||||
| ------------------ | ------ | ------------------------------------------------------------------------------------------------------------- |
|
||||
| 意见反馈入库 | 已实现 | 用户在 Workspace/Chat 提交意见后写入 `general_feedbacks`,后台报表可查看 |
|
||||
| 反馈企业微信群通知 | 已实现 | 反馈入库后通过 `WECOM_FEEDBACK_BOT_WEBHOOK` 即时推送到企业微信群;未配置 webhook 时静默跳过,不影响用户提交 |
|
||||
| 反馈截图附件 | 已实现 | 意见反馈支持粘贴/上传截图附件(每条最多 5 张),管理端报表可查看附图缩略图与大图预览 |
|
||||
|
||||
## 知识库内容清单按钮(2026-10)
|
||||
|
||||
@@ -691,6 +692,7 @@
|
||||
| 管理端运营总览 | 「数据报表」新增「运营总览」入口:展示对话量/活跃用户/活跃应用/好评率、对话趋势与环比、Top 应用与低使用应用、低评分回答与未处理反馈,复用 chat_logs/feedbacks/general_feedbacks/agents/应用授权数据 | 已实现(数据处理) | P1 |
|
||||
| 管理端问题分析 | 「数据报表」新增「问题分析」入口,第一版为页面骨架与空状态,不伪造数据 | 已实现(骨架) | P2 |
|
||||
| 管理端时间范围统一 | 「数据报表」各数据页时间范围筛选器统一为「近 7 天 / 30 天 / 90 天」,并同步四语言文案 | 已实现 | P1 |
|
||||
| 管理端部门管理(组织树) | 部门管理改为树形组织结构(对应 OA 组织架构,层级来源对齐 ERP HRAO:hrao01 编码 / hrao02 名称 / hrao06 上级 / hrao09 同级排序 / hrao08 隐藏标记):`departments` 表增加 `parent_id`(邻接表)/ `sort_order` / `is_hidden`(迁移 `dp1a2b3c4d5e6`),`name` 全局唯一放开为「同一上级下唯一」;页面为左树右成员面板(OA 组织结构口径,控件已按 Element Plus 迁移规范 Element 化:ElTable/ElPagination/ElTag/ElDialog/ElMessageBox,树行为自定义层级结构),树顶公司层为前端按 `company` 字段虚拟分组不入库;节点支持添加子部门/编辑/删除(有下级或有员工禁删)、搜索命中自动展开、全部展开/收起;员工展示改为 OA 组织结构口径(左树右成员面板):树表员工计数列剔除,点击部门节点右侧分页展示成员名单(关键词搜索姓名/工号/邮箱/手机、每页 20/50/100 可调,「含下级部门」口径可切换,成员接口 `members` 支持 keyword/page/page_size);新增错误码 `DEPT.*` 四语言。ERP 一次性导入脚本已提供(`backend/scripts/import_departments_from_hrao.py`:DBeaver 导出 HRAO_FILE CSV + 公司映射取自 HRAA_FILE,dry-run 默认、`--apply` 按编码 upsert 合并、悬空/成环/重名告警兜底),已于 2026-10-08 执行首次全量导入(366 部门 / 7 公司,本地 56 行全部按编码命中更新);持续同步仍未做 | 已实现 | P1 |
|
||||
| 管理端常用问题模糊匹配 | 「常用问题」编辑弹窗新增「启用模糊匹配」开关与阈值(0.50–1.00,默认 0.80,逐条目独立、以启用 FAQ 缓存为前提):精确未命中时按相似度兜底直答,容忍加前后缀与近义词差异;得分取 max(编辑距离相似度, 包含覆盖率),命中方式与得分写入 ChatLog payload(match_type / match_score / matched_text) | 已实现 | P2 |
|
||||
|
||||
---
|
||||
|
||||
@@ -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` 已同步更新。
|
||||
@@ -200,7 +200,7 @@ section.admin-table-section 一张圆角卡片,页面上只此一层
|
||||
| 用户管理 | 列表、筛选、三个业务弹窗、删除和改角色确认已按 §3、§4 对齐。筛选宽度和两列表单写在页面里。 |
|
||||
| 知识库分组 | 列表骨架、行内链接按钮、删除确认、创建分组、Dify 设置和健康检查已对齐。 |
|
||||
| 应用配置 | 列表、状态标签、测试弹窗、授权弹窗、删除确认和 680px 创建/编辑表单内部已对齐。保存仍走原来的 `save` 事件。 |
|
||||
| 部门管理 | 列表已用 `AdminListPage`。搜索、表头排序、行内链接、480px 表单、员工名单和删除确认已按 §3、§4 对齐。列表仍是本地过滤和排序,没有分页。 |
|
||||
| 部门管理 | 已改为左树右成员面板的组织树页(非 AdminListPage 列表骨架,页面头注释有说明)。树行内链接按钮、成员 ElTable/ElPagination/ElTag、680px 表单(含上级部门/同级排序/隐藏标记)和 ElMessageBox 删除确认已按 §4 对齐;成员分页走服务端。 |
|
||||
| 公告管理 | 列表已用 `AdminListPage`。发布/编辑是 680px 对话框,详情是描述列表,删除确认已对齐。 |
|
||||
| 关联服务 | 列表已用 `AdminListPage`。启用用 `ElSwitch`,表单 480px,删除确认已对齐。 |
|
||||
| 知识库分组 | 外层不再套第二张卡片,列表骨架改为 `AdminListPage`。 |
|
||||
|
||||
@@ -584,10 +584,24 @@ export const updateAdminUserPermissions = (userId: number, agentIds: number[]) =
|
||||
body: JSON.stringify({ agent_ids: agentIds }),
|
||||
});
|
||||
|
||||
// Departments
|
||||
// Departments(树形结构:/tree 返回 children 嵌套,成员支持含下级)
|
||||
export const listAdminDepartments = () => requestJson<any[]>('/api/admin/departments', auth());
|
||||
export const listAdminDepartmentMembers = (id: number) =>
|
||||
requestJson(`/api/admin/departments/${id}/members`, auth());
|
||||
export const listAdminDepartmentTree = () => requestJson<any[]>('/api/admin/departments/tree', auth());
|
||||
export interface AdminDepartmentMembersQuery {
|
||||
includeDescendants?: boolean;
|
||||
keyword?: string;
|
||||
page?: number;
|
||||
pageSize?: number;
|
||||
}
|
||||
export const listAdminDepartmentMembers = (id: number, query: AdminDepartmentMembersQuery = {}) => {
|
||||
const params = new URLSearchParams();
|
||||
if (query.includeDescendants) params.set('include_descendants', '1');
|
||||
if (query.keyword?.trim()) params.set('keyword', query.keyword.trim());
|
||||
if (query.page && query.page > 1) params.set('page', String(query.page));
|
||||
if (query.pageSize && query.pageSize !== 20) params.set('page_size', String(query.pageSize));
|
||||
const qs = params.toString();
|
||||
return requestJson(`/api/admin/departments/${id}/members${qs ? `?${qs}` : ''}`, auth());
|
||||
};
|
||||
export const createAdminDepartment = (payload: Record<string, unknown>) =>
|
||||
requestJson('/api/admin/departments', { method: 'POST', ...jsonAuth(), body: JSON.stringify(payload) });
|
||||
export const updateAdminDepartment = (id: number, payload: Record<string, unknown>) =>
|
||||
@@ -912,6 +926,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',
|
||||
|
||||
@@ -1,219 +1,492 @@
|
||||
/**
|
||||
* features/admin/modules/departments/DepartmentsPage.vue
|
||||
* 用途:部门管理列表。一张卡片里放标题、添加按钮、搜索、表格。
|
||||
* 依赖:AdminListPage、useDepartmentsAdmin、element-plus、部门表单和员工名单弹窗。
|
||||
* 逻辑:路由 /admin/departments。骨架用 AdminListPage。筛选、列和两个弹窗留在本页。
|
||||
* 名称、编码、公司用表头排序,排的是当前过滤结果。删除用 Element 确认框。
|
||||
* 表格用 Element stripe 斑马纹。员工数、编辑、删除用 Element 链接按钮,悬停文案走 i18n title。
|
||||
* 用途:部门管理独立页面——左树(公司虚拟分组 + 部门层级)右成员面板(OA 组织结构口径)。
|
||||
* 依赖:useDepartmentsAdmin、DepartmentFormModal、element-plus、@element-plus/icons-vue。
|
||||
* 逻辑:路由 /admin/departments。左侧点击部门节点后,右侧按分页 + 关键词展示该部门成员
|
||||
* (含下级口径可切换);删除确认走 ElMessageBox。控件按 ELEMENT_MIGRATION.md 全量 Element 化,
|
||||
* 树本身是自定义层级结构,不是 ElTable/ElTree 列表页,故不走 AdminListPage 骨架。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue';
|
||||
import { computed, onMounted } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { Delete, Edit, Plus, User } from '@element-plus/icons-vue';
|
||||
import { ElButton, ElCheckbox, ElConfigProvider, ElEmpty, ElIcon, ElInput, ElLoading, ElPagination, ElTable, ElTableColumn, ElTag } from 'element-plus';
|
||||
import {
|
||||
ElButton,
|
||||
ElInput,
|
||||
ElLoading,
|
||||
ElTable,
|
||||
ElTableColumn,
|
||||
} from 'element-plus';
|
||||
ArrowDown,
|
||||
ArrowRight,
|
||||
Delete,
|
||||
Edit,
|
||||
Expand,
|
||||
Fold,
|
||||
FolderAdd,
|
||||
Hide,
|
||||
OfficeBuilding,
|
||||
Plus,
|
||||
Search,
|
||||
} from '@element-plus/icons-vue';
|
||||
import DepartmentFormModal from './components/DepartmentFormModal.vue';
|
||||
import { useDepartmentsAdmin } from './composables/useDepartmentsAdmin';
|
||||
import { useElementProvider } from '@/features/admin/composables/useElementProvider';
|
||||
import type { AdminDepartmentTreeNode } from '@/features/admin/types/admin.types';
|
||||
import 'element-plus/dist/index.css';
|
||||
import 'element-plus/theme-chalk/dark/css-vars.css';
|
||||
import '@/features/admin/styles/element-trial.css';
|
||||
import AdminListPage from '@/features/admin/components/AdminListPage.vue';
|
||||
import type { AdminDepartmentMembersResponse, AdminDepartmentRow } from '@/features/admin/types/admin.types';
|
||||
import DepartmentFormModal from './components/DepartmentFormModal.vue';
|
||||
import DepartmentMembersModal from './components/DepartmentMembersModal.vue';
|
||||
import { useDepartmentsAdmin, type DeptSortKey } from './composables/useDepartmentsAdmin';
|
||||
import { listAdminDepartmentMembers } from '@/features/admin/api/admin.api';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
|
||||
const vLoading = ElLoading.directive;
|
||||
|
||||
const { t } = useI18n();
|
||||
const msg = useMessage();
|
||||
const showMembersModal = ref(false);
|
||||
const departmentMembers = ref<AdminDepartmentMembersResponse | null>(null);
|
||||
const { t, te } = useI18n();
|
||||
const { elementLocale } = useElementProvider();
|
||||
|
||||
const {
|
||||
filteredDepartments,
|
||||
displayRows,
|
||||
parentOptions,
|
||||
form,
|
||||
searchQuery,
|
||||
sortKey,
|
||||
sortDir,
|
||||
isLoading,
|
||||
isListLoading,
|
||||
isSaving,
|
||||
showFormModal,
|
||||
loadAll,
|
||||
applySort,
|
||||
toggleNode,
|
||||
toggleCompany,
|
||||
expandAll,
|
||||
collapseAll,
|
||||
openCreateModal,
|
||||
openEditModal,
|
||||
closeFormModal,
|
||||
saveDepartment,
|
||||
deleteDepartment,
|
||||
selectedDeptId,
|
||||
selectedDept,
|
||||
selectedDeptPath,
|
||||
memberData,
|
||||
memberLoading,
|
||||
memberKeyword,
|
||||
memberIncludeDescendants,
|
||||
memberPage,
|
||||
memberPageSize,
|
||||
selectDept,
|
||||
setMemberKeyword,
|
||||
setMemberIncludeDescendants,
|
||||
setMemberPage,
|
||||
setMemberPageSize,
|
||||
} = useDepartmentsAdmin();
|
||||
|
||||
const defaultSort = computed(() => ({
|
||||
prop: sortKey.value || 'name',
|
||||
order: sortDir.value === 'desc' ? 'descending' as const : 'ascending' as const,
|
||||
}));
|
||||
/** 成员面板总页数(由 total / page_size 推导)。 */
|
||||
const memberTotalPages = computed(() => {
|
||||
const data = memberData.value;
|
||||
if (!data || data.page_size <= 0) return 1;
|
||||
return Math.max(1, Math.ceil(data.total / data.page_size));
|
||||
});
|
||||
|
||||
const emptyText = computed(() => (
|
||||
/** 左树空状态文案:搜索无结果或尚无部门。 */
|
||||
const treeEmptyText = computed(() => (
|
||||
searchQuery.value.trim() ? t('admin.dept.noSearchResults') : t('admin.dept.noDepts')
|
||||
));
|
||||
|
||||
/**
|
||||
* 把 Element 表头排序交给本地列表。
|
||||
* 核心逻辑:只接受名称、编码、公司;第三次点击 order 为空时清空排序。
|
||||
* @param payload.prop - 列字段
|
||||
* @param payload.order - ascending、descending 或空
|
||||
*/
|
||||
function onSortChange(payload: { prop: string | null; order: string | null }): void {
|
||||
const field = payload.prop;
|
||||
const sortable = field === 'name' || field === 'code' || field === 'company';
|
||||
if (sortable && payload.order) {
|
||||
applySort(field as DeptSortKey, payload.order === 'descending' ? 'desc' : 'asc');
|
||||
return;
|
||||
}
|
||||
applySort('', '');
|
||||
}
|
||||
/** 成员状态 → 本地化标签;未知状态回退显示原值。 */
|
||||
const statusLabel = (status?: string): string => {
|
||||
if (!status) return '-';
|
||||
const key = `admin.dept.members.status.${status}`;
|
||||
return te(key) ? t(key) : status;
|
||||
};
|
||||
|
||||
/**
|
||||
* 打开编辑弹窗。表格插槽行类型较宽,这里收成部门行。
|
||||
* @param row - 当前表格行
|
||||
*/
|
||||
function editDepartment(row: AdminDepartmentRow): void {
|
||||
openEditModal(row);
|
||||
}
|
||||
/** 成员状态 → ElTag 类型:启用 success,待审核 warning,其余 info。 */
|
||||
const statusTagType = (status?: string): 'success' | 'warning' | 'info' => {
|
||||
if (status === 'active') return 'success';
|
||||
if (status === 'pending') return 'warning';
|
||||
return 'info';
|
||||
};
|
||||
|
||||
/**
|
||||
* 加载并展示指定部门的员工名单。
|
||||
* 核心逻辑:请求成功才打开弹窗;失败只提示,不打开空名单。
|
||||
* @param departmentId - 部门主键
|
||||
*/
|
||||
async function openDepartmentMembers(departmentId: number): Promise<void> {
|
||||
try {
|
||||
departmentMembers.value = await listAdminDepartmentMembers(departmentId) as AdminDepartmentMembersResponse;
|
||||
showMembersModal.value = true;
|
||||
} catch (error) {
|
||||
msg.error((error as Error).message || t('admin.msg.requestFailed'));
|
||||
}
|
||||
}
|
||||
/** 公司虚拟分组行 key 去前缀,得到分组 key(用于展开状态)。 */
|
||||
const companyGroupKey = (rowKey: string): string => rowKey.slice('company:'.length);
|
||||
|
||||
onMounted(() => {
|
||||
// 【版本标记】用于核对浏览器加载的是否为本版代码;确认后可移除
|
||||
console.info('[departments] UI build v8 (2026-10-30): 树列贴合内容/成员表580定宽居中/默认展开第一层/两栏独立滚动');
|
||||
void loadAll();
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<AdminListPage :loading="isLoading">
|
||||
<template #title>
|
||||
<h2 class="section-title">{{ t('admin.dept.title') }}</h2>
|
||||
<p class="section-desc mt-1">{{ t('admin.dept.subtitle') }}</p>
|
||||
</template>
|
||||
<template #actions>
|
||||
<ElButton type="primary" :icon="Plus" @click="openCreateModal">
|
||||
<ElConfigProvider :locale="elementLocale">
|
||||
<!-- 高度/布局写内联样式:外层内容列不再出现整页滚动条,滚动只发生在左右两栏各自内部 -->
|
||||
<section
|
||||
class="admin-table-section admin-dept-page"
|
||||
style="height: 100%; min-height: 0; display: flex; flex-direction: column; overflow: hidden;"
|
||||
>
|
||||
<header class="admin-table-header admin-table-header--stacked">
|
||||
<div>
|
||||
<h2 class="section-title">{{ t('admin.dept.title') }}</h2>
|
||||
<p class="section-desc mt-1">{{ t('admin.dept.subtitle') }}</p>
|
||||
</div>
|
||||
<ElButton type="primary" :icon="Plus" @click="openCreateModal()">
|
||||
{{ t('admin.dept.add') }}
|
||||
</ElButton>
|
||||
</template>
|
||||
<template #filters>
|
||||
</header>
|
||||
|
||||
<!-- 筛选条:左树搜索 + 展开/收起,一条分隔线与内容区分开 -->
|
||||
<div class="admin-dept-filter">
|
||||
<ElInput
|
||||
v-model="searchQuery"
|
||||
class="admin-dept-filter__search"
|
||||
:prefix-icon="Search"
|
||||
clearable
|
||||
class="dept-filter-search"
|
||||
:placeholder="t('admin.dept.searchPlaceholder')"
|
||||
/>
|
||||
</template>
|
||||
<ElButton text :icon="Expand" :title="t('admin.dept.expandAll')" @click="expandAll" />
|
||||
<ElButton text :icon="Fold" :title="t('admin.dept.collapseAll')" @click="collapseAll" />
|
||||
</div>
|
||||
|
||||
<ElTable
|
||||
v-loading="isListLoading"
|
||||
class="hx-admin-table"
|
||||
:data="filteredDepartments"
|
||||
row-key="id"
|
||||
stripe
|
||||
:default-sort="defaultSort"
|
||||
:empty-text="emptyText"
|
||||
@sort-change="onSortChange"
|
||||
>
|
||||
<ElTableColumn prop="name" :label="t('admin.dept.headers.name')" sortable="custom" min-width="200">
|
||||
<template #default="{ row }">
|
||||
<div :title="row.name">{{ row.name }}</div>
|
||||
<p v-if="row.description" class="hx-element-hint dept-desc" :title="row.description">
|
||||
{{ row.description }}
|
||||
</p>
|
||||
</template>
|
||||
</ElTableColumn>
|
||||
<ElTableColumn prop="code" :label="t('admin.dept.headers.code')" sortable="custom" min-width="140">
|
||||
<template #default="{ row }">{{ row.code || '-' }}</template>
|
||||
</ElTableColumn>
|
||||
<ElTableColumn prop="company" :label="t('admin.dept.headers.company')" sortable="custom" min-width="180">
|
||||
<template #default="{ row }">{{ row.company || '-' }}</template>
|
||||
</ElTableColumn>
|
||||
<ElTableColumn :label="t('admin.dept.headers.members')" width="120" align="center">
|
||||
<template #default="{ row }">
|
||||
<ElButton
|
||||
link
|
||||
type="primary"
|
||||
:icon="User"
|
||||
:title="t('admin.dept.actions.viewMembers')"
|
||||
@click="openDepartmentMembers((row as AdminDepartmentRow).id)"
|
||||
<div v-loading="isLoading" class="admin-dept-body" style="flex: 1; min-height: 0; display: flex; align-items: stretch; overflow-x: auto;">
|
||||
<!-- 左侧:组织树(公司虚拟分组 + 层级缩进);定宽写在 style 上,避免 HMR 样式层滞后导致宽度不生效 -->
|
||||
<div class="admin-dept-tree" style="width: max-content; min-width: 260px; max-width: 45%; flex-shrink: 0;">
|
||||
<ElEmpty v-if="displayRows.length === 0" :description="treeEmptyText" :image-size="80" />
|
||||
<template v-for="row in displayRows" :key="row.key">
|
||||
<!-- 公司虚拟分组行(不入库,前端按 company 字段归堆) -->
|
||||
<div
|
||||
v-if="row.kind === 'company'"
|
||||
class="admin-dept-tree__row admin-dept-tree__row--company"
|
||||
@click="toggleCompany(companyGroupKey(row.key))"
|
||||
>
|
||||
{{ row.member_count || 0 }}
|
||||
</ElButton>
|
||||
</template>
|
||||
</ElTableColumn>
|
||||
<ElTableColumn :label="t('admin.dept.headers.actions')" width="120" align="right">
|
||||
<template #default="{ row }">
|
||||
<div class="dept-row-actions">
|
||||
<ElIcon class="admin-dept-tree__chevron">
|
||||
<component :is="row.expanded ? ArrowDown : ArrowRight" />
|
||||
</ElIcon>
|
||||
<ElIcon class="admin-dept-tree__company-icon"><OfficeBuilding /></ElIcon>
|
||||
<span class="admin-dept-tree__name" :title="row.company">{{ row.company }}</span>
|
||||
<ElButton
|
||||
link
|
||||
type="primary"
|
||||
:icon="Edit"
|
||||
:title="t('admin.dept.actions.edit')"
|
||||
@click="editDepartment(row as AdminDepartmentRow)"
|
||||
/>
|
||||
<ElButton
|
||||
link
|
||||
type="danger"
|
||||
:icon="Delete"
|
||||
:title="t('admin.dept.actions.delete')"
|
||||
@click="deleteDepartment((row as AdminDepartmentRow).id)"
|
||||
:icon="FolderAdd"
|
||||
:title="t('admin.dept.addChild')"
|
||||
@click.stop="openCreateModal(null, row.company)"
|
||||
/>
|
||||
</div>
|
||||
<!-- 部门行(层级缩进;点击选中 → 右侧出成员面板) -->
|
||||
<div
|
||||
v-else
|
||||
class="admin-dept-tree__row"
|
||||
:class="{ 'is-selected': selectedDeptId === row.node!.id }"
|
||||
:style="{ paddingLeft: `${(row.depth - 1) * 16 + 4}px` }"
|
||||
@click="selectDept(row.node!)"
|
||||
>
|
||||
<button
|
||||
v-if="row.hasChildren"
|
||||
type="button"
|
||||
class="admin-dept-tree__toggle"
|
||||
:title="row.expanded ? t('admin.dept.collapse') : t('admin.dept.expand')"
|
||||
@click.stop="toggleNode(row.node!.id)"
|
||||
>
|
||||
<ElIcon>
|
||||
<component :is="row.expanded ? ArrowDown : ArrowRight" />
|
||||
</ElIcon>
|
||||
</button>
|
||||
<span v-else class="admin-dept-tree__toggle" />
|
||||
<span class="admin-dept-tree__name" :title="row.node!.name">{{ row.node!.name }}</span>
|
||||
<ElTag
|
||||
v-if="row.node!.is_hidden"
|
||||
type="warning"
|
||||
effect="light"
|
||||
size="small"
|
||||
:icon="Hide"
|
||||
:title="t('admin.dept.fields.hiddenHint')"
|
||||
>
|
||||
{{ t('admin.dept.tags.hidden') }}
|
||||
</ElTag>
|
||||
<span class="admin-dept-tree__spacer" />
|
||||
<span class="admin-dept-tree__actions" @click.stop>
|
||||
<ElButton
|
||||
link
|
||||
type="primary"
|
||||
:icon="FolderAdd"
|
||||
:title="t('admin.dept.addChild')"
|
||||
@click="openCreateModal(row.node as AdminDepartmentTreeNode)"
|
||||
/>
|
||||
<ElButton
|
||||
link
|
||||
type="primary"
|
||||
:icon="Edit"
|
||||
:title="t('admin.dept.actions.edit')"
|
||||
@click="openEditModal(row.node!)"
|
||||
/>
|
||||
<ElButton
|
||||
link
|
||||
type="danger"
|
||||
:icon="Delete"
|
||||
:title="t('admin.dept.actions.delete')"
|
||||
@click="deleteDepartment(row.node!.id)"
|
||||
/>
|
||||
</span>
|
||||
</div>
|
||||
</template>
|
||||
</ElTableColumn>
|
||||
</ElTable>
|
||||
</AdminListPage>
|
||||
</div>
|
||||
|
||||
<!-- 右侧:选中部门的成员面板(OA 口径) -->
|
||||
<div class="admin-dept-members" style="flex: 1; min-width: 280px; min-height: 0; display: flex; flex-direction: column;">
|
||||
<template v-if="!selectedDept">
|
||||
<ElEmpty class="admin-dept-members__empty" :description="t('admin.dept.members.hint')" :image-size="80" />
|
||||
</template>
|
||||
<template v-else>
|
||||
<header class="admin-dept-members__header">
|
||||
<div class="admin-dept-members__title">
|
||||
<h3>{{ selectedDept.name }}</h3>
|
||||
<p :title="selectedDeptPath.join(' / ')">{{ selectedDeptPath.join(' / ') }}</p>
|
||||
</div>
|
||||
<ElCheckbox
|
||||
:model-value="memberIncludeDescendants"
|
||||
@change="setMemberIncludeDescendants($event as boolean)"
|
||||
>
|
||||
{{ t('admin.dept.members.includeDescendants') }}
|
||||
</ElCheckbox>
|
||||
</header>
|
||||
|
||||
<div class="admin-dept-members__toolbar">
|
||||
<ElInput
|
||||
:model-value="memberKeyword"
|
||||
class="admin-dept-members__search"
|
||||
:prefix-icon="Search"
|
||||
clearable
|
||||
:placeholder="t('admin.dept.members.searchPlaceholder')"
|
||||
@input="setMemberKeyword(String($event))"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div v-loading="memberLoading" class="admin-dept-members__tablewrap" style="flex: 1 1 0; min-height: 0; width: 600px; max-width: 100%; margin-inline: auto;">
|
||||
<ElTable
|
||||
:data="memberData?.members ?? []"
|
||||
row-key="id"
|
||||
stripe
|
||||
height="100%"
|
||||
:empty-text="t('admin.dept.members.empty')"
|
||||
>
|
||||
<ElTableColumn :label="t('admin.dept.members.columns.name')" width="170">
|
||||
<template #default="{ row }">
|
||||
<div class="admin-dept-member__name">{{ row.real_name || row.username }}</div>
|
||||
<div class="admin-dept-member__sub">{{ row.username }}</div>
|
||||
</template>
|
||||
</ElTableColumn>
|
||||
<ElTableColumn :label="t('admin.dept.members.columns.contact')" width="150" show-overflow-tooltip>
|
||||
<template #default="{ row }">{{ row.phone_number || row.email || '-' }}</template>
|
||||
</ElTableColumn>
|
||||
<ElTableColumn prop="employee_id" :label="t('admin.dept.members.columns.employeeId')" width="90" show-overflow-tooltip />
|
||||
<ElTableColumn prop="department" :label="t('admin.dept.members.columns.department')" width="110" show-overflow-tooltip />
|
||||
<ElTableColumn :label="t('admin.dept.members.columns.status')" width="80">
|
||||
<template #default="{ row }">
|
||||
<ElTag :type="statusTagType(row.status)" effect="light" size="small">
|
||||
{{ statusLabel(row.status) }}
|
||||
</ElTag>
|
||||
</template>
|
||||
</ElTableColumn>
|
||||
</ElTable>
|
||||
</div>
|
||||
|
||||
<footer v-if="memberData" class="admin-dept-members__footer" style="width: 600px; max-width: 100%; margin-inline: auto; display: flex; align-items: center; justify-content: flex-end; flex-wrap: wrap; row-gap: 8px; gap: 12px; padding: 12px 0; border-top: 1px solid var(--el-border-color-lighter);">
|
||||
<ElPagination
|
||||
background
|
||||
layout="total, sizes, prev, pager, next"
|
||||
:total="memberData.total"
|
||||
:current-page="memberPage"
|
||||
:page-size="memberPageSize"
|
||||
:page-sizes="[20, 50, 100]"
|
||||
@current-change="setMemberPage"
|
||||
@size-change="setMemberPageSize"
|
||||
/>
|
||||
<span class="admin-dept-members__pages">{{ memberPage }} / {{ memberTotalPages }}</span>
|
||||
</footer>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<DepartmentFormModal
|
||||
:visible="showFormModal"
|
||||
:form="form"
|
||||
:parent-options="parentOptions"
|
||||
:is-saving="isSaving"
|
||||
@close="closeFormModal"
|
||||
@save="saveDepartment"
|
||||
/>
|
||||
<DepartmentMembersModal
|
||||
:visible="showMembersModal"
|
||||
:data="departmentMembers"
|
||||
@close="showMembersModal = false"
|
||||
/>
|
||||
</ElConfigProvider>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
:deep(.dept-filter-search) {
|
||||
/* 页内布局(非 Element 控件内部),间距对齐迁移规范:筛选条、面板分隔、分页右侧 */
|
||||
/* AdminLayout 内容列高度确定(h-dvh 壳内 flex-1 min-h-0),本页卡片填满后左右两栏各自滚动 */
|
||||
.admin-dept-page {
|
||||
height: 100%;
|
||||
min-height: 24rem;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
.admin-dept-filter {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 12px 32px;
|
||||
border-bottom: 1px solid var(--el-border-color-lighter);
|
||||
}
|
||||
.admin-dept-filter__search {
|
||||
width: 16rem;
|
||||
}
|
||||
|
||||
.dept-desc {
|
||||
.admin-dept-body {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
align-items: stretch;
|
||||
overflow-x: auto;
|
||||
}
|
||||
.admin-dept-tree {
|
||||
width: max-content;
|
||||
min-width: 260px;
|
||||
max-width: 45%;
|
||||
flex-shrink: 0;
|
||||
padding: 12px 8px 12px 24px;
|
||||
border-right: 1px solid var(--el-border-color-lighter);
|
||||
overflow-y: auto;
|
||||
}
|
||||
.admin-dept-tree__row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
padding: 6px 4px;
|
||||
border-radius: var(--el-border-radius-base);
|
||||
cursor: pointer;
|
||||
user-select: none;
|
||||
min-width: 0;
|
||||
}
|
||||
.admin-dept-tree__row:hover {
|
||||
background: var(--el-fill-color-light);
|
||||
}
|
||||
.admin-dept-tree__row--company {
|
||||
font-weight: 600;
|
||||
}
|
||||
.admin-dept-tree__row.is-selected {
|
||||
background: var(--el-color-primary-light-9);
|
||||
}
|
||||
.admin-dept-tree__row.is-selected .admin-dept-tree__name {
|
||||
color: var(--el-color-primary);
|
||||
}
|
||||
.admin-dept-tree__chevron,
|
||||
.admin-dept-tree__toggle {
|
||||
flex-shrink: 0;
|
||||
width: 20px;
|
||||
display: inline-flex;
|
||||
justify-content: center;
|
||||
color: var(--el-text-color-secondary);
|
||||
background: none;
|
||||
border: none;
|
||||
padding: 0;
|
||||
cursor: pointer;
|
||||
}
|
||||
.admin-dept-tree__company-icon {
|
||||
flex-shrink: 0;
|
||||
color: var(--el-color-primary);
|
||||
}
|
||||
.admin-dept-tree__name {
|
||||
font-size: var(--el-font-size-base);
|
||||
color: var(--el-text-color-primary);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
.admin-dept-tree__spacer {
|
||||
flex: 1;
|
||||
}
|
||||
.admin-dept-tree__actions {
|
||||
display: none;
|
||||
align-items: center;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.admin-dept-tree__row:hover .admin-dept-tree__actions {
|
||||
display: inline-flex;
|
||||
}
|
||||
.admin-dept-members {
|
||||
flex: 1;
|
||||
min-width: 280px;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
.admin-dept-members__empty {
|
||||
flex: 1;
|
||||
margin: auto;
|
||||
}
|
||||
.admin-dept-members__header {
|
||||
/* width 由 .admin-dept-members 统一定宽 */
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
flex-wrap: wrap;
|
||||
padding: 16px 24px 8px;
|
||||
}
|
||||
.admin-dept-members__title {
|
||||
min-width: 0;
|
||||
}
|
||||
.admin-dept-members__title h3 {
|
||||
font-size: var(--el-font-size-large);
|
||||
font-weight: 600;
|
||||
color: var(--el-text-color-primary);
|
||||
margin: 0;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
.admin-dept-members__title p {
|
||||
font-size: var(--el-font-size-small);
|
||||
color: var(--el-text-color-secondary);
|
||||
margin: 2px 0 0;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
.admin-dept-members__toolbar {
|
||||
padding: 8px 24px 12px;
|
||||
border-bottom: 1px solid var(--el-border-color-lighter);
|
||||
}
|
||||
.admin-dept-members__search {
|
||||
width: 16rem;
|
||||
}
|
||||
.admin-dept-members__tablewrap {
|
||||
/* 宽度须与上方五列 width 之和(170+150+90+110+80=600)保持一致;居中使剩余空白均匀分两侧 */
|
||||
width: 600px;
|
||||
max-width: 100%;
|
||||
margin-inline: auto;
|
||||
}
|
||||
.admin-dept-members__footer {
|
||||
/* 与表格同宽并同样居中,分页对齐表格右缘 */
|
||||
width: 600px;
|
||||
max-width: 100%;
|
||||
margin-inline: auto;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
flex-wrap: wrap;
|
||||
row-gap: 8px;
|
||||
gap: 12px;
|
||||
padding: 12px 0;
|
||||
border-top: 1px solid var(--el-border-color-lighter);
|
||||
}
|
||||
.admin-dept-members__pages {
|
||||
font-size: var(--el-font-size-small);
|
||||
color: var(--el-text-color-secondary);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.dept-row-actions {
|
||||
display: inline-flex;
|
||||
justify-content: flex-end;
|
||||
gap: 4px;
|
||||
.admin-dept-member__name {
|
||||
color: var(--el-text-color-primary);
|
||||
}
|
||||
.admin-dept-member__sub {
|
||||
font-size: var(--el-font-size-extra-small);
|
||||
color: var(--el-text-color-secondary);
|
||||
margin-top: 2px;
|
||||
}
|
||||
@media (max-width: 1023px) {
|
||||
.admin-dept-body {
|
||||
flex-direction: column;
|
||||
}
|
||||
.admin-dept-tree {
|
||||
max-height: 40vh;
|
||||
}
|
||||
.admin-dept-members {
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
+91
-13
@@ -1,17 +1,20 @@
|
||||
/**
|
||||
/**
|
||||
* features/admin/modules/departments/components/DepartmentFormModal.vue
|
||||
* 用途:部门创建和编辑对话框。四个字段,单列。
|
||||
* 依赖:element-plus 对话框和表单、DepartmentFormState。
|
||||
* 逻辑:DepartmentsPage 打开本组件。提交时 emit save,由 useDepartmentsAdmin 调接口。样式跟页面已引入的 Element 皮肤走。
|
||||
* 用途:部门创建/编辑对话框(上级部门选择、同级排序、隐藏标记)。
|
||||
* 依赖:element-plus 对话框和表单、DepartmentFormState、DeptParentOption。
|
||||
* 逻辑:DepartmentsPage 打开本组件。上级选项由父级传入(编辑时已排除自身及子孙,防成环);
|
||||
* 公司未填时由后端继承上级部门;提交时 emit save,由 useDepartmentsAdmin 调接口。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { ElButton, ElDialog, ElForm, ElFormItem, ElInput } from 'element-plus';
|
||||
import { ElButton, ElCol, ElDialog, ElForm, ElFormItem, ElInput, ElInputNumber, ElOption, ElRow, ElSelect, ElSwitch } from 'element-plus';
|
||||
import type { DepartmentFormState } from '@/features/admin/types/department.types';
|
||||
import type { DeptParentOption } from '../composables/useDepartmentsAdmin';
|
||||
|
||||
defineProps<{
|
||||
const props = defineProps<{
|
||||
visible: boolean;
|
||||
form: DepartmentFormState;
|
||||
parentOptions: DeptParentOption[];
|
||||
isSaving: boolean;
|
||||
}>();
|
||||
|
||||
@@ -22,6 +25,14 @@ const emit = defineEmits<{
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
/**
|
||||
* 上级部门下拉回写:ElSelect 不接受 null 类型,空值在此统一为 null(顶级部门)。
|
||||
* @param value - 下拉选中的值
|
||||
*/
|
||||
function onParentChange(value: unknown): void {
|
||||
props.form.parentId = (value ?? null) as number | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 对话框关闭时通知页面收起并重置表单。
|
||||
* @param open - Element 对话框的打开状态
|
||||
@@ -35,7 +46,7 @@ function onVisibleChange(open: boolean): void {
|
||||
<ElDialog
|
||||
:model-value="visible"
|
||||
:title="form.id ? t('admin.dept.edit') : t('admin.dept.add')"
|
||||
width="480px"
|
||||
width="680px"
|
||||
align-center
|
||||
append-to-body
|
||||
:close-on-click-modal="false"
|
||||
@@ -44,15 +55,54 @@ function onVisibleChange(open: boolean): void {
|
||||
@update:model-value="onVisibleChange"
|
||||
>
|
||||
<ElForm label-position="top" :model="form" @submit.prevent="emit('save')">
|
||||
<ElFormItem :label="t('admin.dept.fields.parent')">
|
||||
<!-- 运行时以 null 表示顶级部门(有对应选项),modelValue 的类型限制此处用 as any 放行 -->
|
||||
<ElSelect :model-value="(form.parentId ?? null) as any" filterable @update:model-value="onParentChange">
|
||||
<ElOption
|
||||
v-for="option in parentOptions"
|
||||
:key="String(option.id)"
|
||||
:label="option.label"
|
||||
:value="option.id as number"
|
||||
:disabled="option.disabled"
|
||||
/>
|
||||
</ElSelect>
|
||||
</ElFormItem>
|
||||
<ElFormItem :label="t('admin.dept.fields.name')" required>
|
||||
<ElInput v-model="form.name" :placeholder="t('admin.dept.fields.namePlaceholder')" />
|
||||
</ElFormItem>
|
||||
<ElFormItem :label="t('admin.dept.fields.code')">
|
||||
<ElInput v-model="form.code" :placeholder="t('admin.dept.fields.codePlaceholder')" />
|
||||
</ElFormItem>
|
||||
<ElFormItem :label="t('admin.dept.fields.company')">
|
||||
<ElInput v-model="form.company" :placeholder="t('admin.dept.fields.companyPlaceholder')" />
|
||||
</ElFormItem>
|
||||
<ElRow>
|
||||
<ElCol :span="12" class="admin-dept-form__col">
|
||||
<ElFormItem :label="t('admin.dept.fields.code')">
|
||||
<ElInput v-model="form.code" :placeholder="t('admin.dept.fields.codePlaceholder')" />
|
||||
</ElFormItem>
|
||||
</ElCol>
|
||||
<ElCol :span="12" class="admin-dept-form__col">
|
||||
<ElFormItem :label="t('admin.dept.fields.company')">
|
||||
<ElInput v-model="form.company" :placeholder="t('admin.dept.fields.companyPlaceholder')" />
|
||||
</ElFormItem>
|
||||
</ElCol>
|
||||
</ElRow>
|
||||
<ElRow>
|
||||
<ElCol :span="12" class="admin-dept-form__col">
|
||||
<ElFormItem :label="t('admin.dept.fields.sort')">
|
||||
<ElInputNumber
|
||||
:model-value="form.sortOrder ?? 0"
|
||||
:min="0"
|
||||
class="admin-dept-form__number"
|
||||
@update:model-value="form.sortOrder = $event ?? 0"
|
||||
/>
|
||||
</ElFormItem>
|
||||
</ElCol>
|
||||
<ElCol :span="12" class="admin-dept-form__col">
|
||||
<ElFormItem :label="t('admin.dept.fields.visibility')">
|
||||
<div class="admin-dept-form__switch">
|
||||
<ElSwitch v-model="form.isHidden" />
|
||||
<span class="admin-dept-form__switch-label">{{ t('admin.dept.fields.hidden') }}</span>
|
||||
</div>
|
||||
<p class="admin-dept-form__hint">{{ t('admin.dept.fields.hiddenHint') }}</p>
|
||||
</ElFormItem>
|
||||
</ElCol>
|
||||
</ElRow>
|
||||
<ElFormItem :label="t('admin.dept.fields.description')">
|
||||
<ElInput
|
||||
v-model="form.description"
|
||||
@@ -70,3 +120,31 @@ function onVisibleChange(open: boolean): void {
|
||||
</template>
|
||||
</ElDialog>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.admin-dept-form__col {
|
||||
padding-right: 16px;
|
||||
}
|
||||
.admin-dept-form__col:last-child {
|
||||
padding-right: 0;
|
||||
}
|
||||
.admin-dept-form__number {
|
||||
width: 100%;
|
||||
}
|
||||
.admin-dept-form__switch {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding-top: 4px;
|
||||
}
|
||||
.admin-dept-form__switch-label {
|
||||
font-size: var(--el-font-size-base);
|
||||
color: var(--el-text-color-regular);
|
||||
}
|
||||
.admin-dept-form__hint {
|
||||
font-size: var(--el-font-size-extra-small);
|
||||
color: var(--el-text-color-secondary);
|
||||
margin: 4px 0 0;
|
||||
line-height: 1.5;
|
||||
}
|
||||
</style>
|
||||
@@ -1,72 +0,0 @@
|
||||
/**
|
||||
* features/admin/modules/departments/components/DepartmentMembersModal.vue
|
||||
* 用途:只读展示某个部门的员工数量和名单。
|
||||
* 依赖:element-plus 对话框和表格、部门成员响应类型。
|
||||
* 逻辑:DepartmentsPage 拉到名单后传入。本组件不请求接口,只展示和关闭。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { ElButton, ElDialog, ElTable, ElTableColumn } from 'element-plus';
|
||||
import type { AdminDepartmentMembersResponse } from '@/features/admin/types/admin.types';
|
||||
|
||||
defineProps<{
|
||||
visible: boolean;
|
||||
data: AdminDepartmentMembersResponse | null;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{ close: [] }>();
|
||||
const { t } = useI18n();
|
||||
|
||||
/**
|
||||
* 对话框关闭时通知页面收起。
|
||||
* @param open - Element 对话框的打开状态
|
||||
*/
|
||||
function onVisibleChange(open: boolean): void {
|
||||
if (!open) emit('close');
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<ElDialog
|
||||
:model-value="visible && !!data"
|
||||
:title="data ? t('admin.dept.members.title', { name: data.department.name }) : ''"
|
||||
width="680px"
|
||||
align-center
|
||||
append-to-body
|
||||
:close-on-click-modal="false"
|
||||
@update:model-value="onVisibleChange"
|
||||
>
|
||||
<template v-if="data">
|
||||
<p class="section-desc">{{ t('admin.dept.members.count', { count: data.count }) }}</p>
|
||||
<ElTable
|
||||
class="dept-members-table"
|
||||
:data="data.members"
|
||||
row-key="id"
|
||||
max-height="60vh"
|
||||
:empty-text="t('admin.dept.members.empty')"
|
||||
>
|
||||
<ElTableColumn :label="t('admin.user.fields.realName')" min-width="140">
|
||||
<template #default="{ row }">{{ row.real_name || row.username }}</template>
|
||||
</ElTableColumn>
|
||||
<ElTableColumn :label="t('admin.user.fields.employeeId')" min-width="120">
|
||||
<template #default="{ row }">{{ row.employee_id || '-' }}</template>
|
||||
</ElTableColumn>
|
||||
<ElTableColumn :label="t('admin.user.fields.email')" min-width="180">
|
||||
<template #default="{ row }">{{ row.email || '-' }}</template>
|
||||
</ElTableColumn>
|
||||
<ElTableColumn :label="t('admin.user.headers.status')" min-width="100">
|
||||
<template #default="{ row }">{{ row.status || '-' }}</template>
|
||||
</ElTableColumn>
|
||||
</ElTable>
|
||||
</template>
|
||||
<template #footer>
|
||||
<ElButton @click="emit('close')">{{ t('admin.close') }}</ElButton>
|
||||
</template>
|
||||
</ElDialog>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.dept-members-table {
|
||||
margin-top: 16px;
|
||||
}
|
||||
</style>
|
||||
+353
-77
@@ -1,8 +1,9 @@
|
||||
/**
|
||||
/**
|
||||
* features/admin/modules/departments/composables/useDepartmentsAdmin.ts
|
||||
* 用途:部门管理列表、搜索过滤、列排序、创建/编辑弹窗、删除。
|
||||
* 依赖:admin.api、department.types、useMessage、useTableSort、element-plus 的确认框。
|
||||
* 逻辑:DepartmentsPage 调用本 composable。表头排序由页面把 Element 的 sort-change 交给 applySort,仍在本地对过滤后的列表排序。删除用 ElMessageBox,不再使用 DeleteConfirmDialog。
|
||||
* 用途:部门树加载、公司虚拟分组、展开/收起、搜索过滤、创建/编辑/删除。
|
||||
* 依赖:admin.api、department.types、useMessage、element-plus 的确认框。
|
||||
* 逻辑:DepartmentsPage 调用本 composable;数据来自 /admin/departments/tree(children 已按同级排序号排好);
|
||||
* 公司层不入库,按顶级部门的 company 字段在前端虚拟分组;删除用 ElMessageBox,不再使用 DeleteConfirmDialog。
|
||||
*/
|
||||
import { computed, ref } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
@@ -10,84 +11,310 @@ import { ElMessageBox } from 'element-plus';
|
||||
import {
|
||||
createAdminDepartment,
|
||||
deleteAdminDepartment,
|
||||
listAdminDepartments,
|
||||
listAdminDepartmentMembers,
|
||||
listAdminDepartmentTree,
|
||||
updateAdminDepartment,
|
||||
} from '@/features/admin/api/admin.api';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import { useTableSort } from '@/shared/composables/useTableSort';
|
||||
import type { SortDir } from '@/shared/utils/table-sort';
|
||||
import type { AdminDepartmentRow } from '@/features/admin/types/admin.types';
|
||||
import type {
|
||||
AdminDepartmentMembersResponse,
|
||||
AdminDepartmentTreeNode,
|
||||
} from '@/features/admin/types/admin.types';
|
||||
import {
|
||||
createEmptyDepartmentForm,
|
||||
departmentRowToForm,
|
||||
type DepartmentFormState,
|
||||
} from '@/features/admin/types/department.types';
|
||||
|
||||
/** 部门表可排序列 */
|
||||
export type DeptSortKey = 'name' | 'code' | 'company';
|
||||
/** 表单弹窗「上级部门」下拉选项(编辑时排除自身及子孙,防成环) */
|
||||
export interface DeptParentOption {
|
||||
id: number | null;
|
||||
label: string;
|
||||
disabled: boolean;
|
||||
}
|
||||
|
||||
/** 树表展开后的一行:company 为公司虚拟分组行,dept 为部门行 */
|
||||
export interface DeptTreeDisplayRow {
|
||||
kind: 'company' | 'dept';
|
||||
key: string;
|
||||
/** 缩进层级:公司组为 0,顶级部门为 1,逐层 +1 */
|
||||
depth: number;
|
||||
company?: string;
|
||||
/** dept 行对应的部门节点 */
|
||||
node?: AdminDepartmentTreeNode;
|
||||
expanded: boolean;
|
||||
hasChildren: boolean;
|
||||
/** 含下级递归汇总的成员数 */
|
||||
totalMembers: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* 部门管理页的列表、表单和删除状态。
|
||||
* 核心逻辑:拉全量部门后在本地过滤和排序,保存与删除成功后再拉一次列表。
|
||||
* @returns 页面绑定的状态和打开弹窗、排序、保存、删除方法
|
||||
*/
|
||||
export function useDepartmentsAdmin() {
|
||||
const { t } = useI18n();
|
||||
const msg = useMessage();
|
||||
|
||||
const departments = ref<AdminDepartmentRow[]>([]);
|
||||
const tree = ref<AdminDepartmentTreeNode[]>([]);
|
||||
const form = ref<DepartmentFormState>(createEmptyDepartmentForm());
|
||||
const searchQuery = ref('');
|
||||
const { sortKey, sortDir, sortItems } = useTableSort<DeptSortKey>({
|
||||
initialKey: 'name',
|
||||
initialDir: 'asc',
|
||||
});
|
||||
const isLoading = ref(true);
|
||||
const isListLoading = ref(false);
|
||||
const isSaving = ref(false);
|
||||
const showFormModal = ref(false);
|
||||
|
||||
/**
|
||||
* 先按关键词过滤,再按当前排序列排序。
|
||||
* 核心逻辑:模糊匹配四字段 → useTableSort.sortItems。
|
||||
*/
|
||||
const filteredDepartments = computed(() => {
|
||||
const q = searchQuery.value.trim().toLowerCase();
|
||||
const filtered = q
|
||||
? departments.value.filter((d) => {
|
||||
const haystack = [d.name, d.code, d.company, d.description]
|
||||
.filter(Boolean)
|
||||
.join(' ')
|
||||
.toLowerCase();
|
||||
return haystack.includes(q);
|
||||
})
|
||||
: departments.value;
|
||||
|
||||
return sortItems(
|
||||
filtered,
|
||||
(row, key) => row[key],
|
||||
(a, b) => a.id - b.id,
|
||||
);
|
||||
});
|
||||
/** 展开状态:部门节点 id 集合 / 公司分组 key 集合 */
|
||||
const expandedIds = ref<Set<number>>(new Set());
|
||||
const expandedCompanies = ref<Set<string>>(new Set());
|
||||
|
||||
/**
|
||||
* 拉取部门列表并写入 departments。
|
||||
* 拉取部门树并写入 tree。
|
||||
* @returns Promise<void>
|
||||
*/
|
||||
/** 是否已做过首屏默认展开(只做一次,之后尊重用户的展开/收起操作) */
|
||||
let expandSeeded = false;
|
||||
|
||||
const loadDepartments = async (): Promise<void> => {
|
||||
isListLoading.value = true;
|
||||
try {
|
||||
departments.value = await listAdminDepartments();
|
||||
tree.value = (await listAdminDepartmentTree()) as AdminDepartmentTreeNode[];
|
||||
} catch (e) {
|
||||
console.error('Failed to load departments', e);
|
||||
departments.value = [];
|
||||
} finally {
|
||||
isListLoading.value = false;
|
||||
console.error('Failed to load department tree', e);
|
||||
tree.value = [];
|
||||
}
|
||||
// 首屏默认展开公司组与第一层部门:树内容填满栏高(对齐 OA 展开到第一级的习惯)
|
||||
if (!expandSeeded && tree.value.length) {
|
||||
expandSeeded = true;
|
||||
expandedCompanies.value = new Set(tree.value.map((r) => r.company?.trim() || ''));
|
||||
expandedIds.value = new Set(tree.value.map((r) => r.id));
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 页面初始化:加载部门列表并结束 loading。
|
||||
* 按关键词过滤树:命中节点及其祖先保留;搜索态下全部自动展开。
|
||||
* 核心逻辑:递归 filterTree → 命中自身或子孙的节点保留。
|
||||
*/
|
||||
const displayRows = computed<DeptTreeDisplayRow[]>(() => {
|
||||
const q = searchQuery.value.trim().toLowerCase();
|
||||
|
||||
const filterTree = (nodes: AdminDepartmentTreeNode[]): AdminDepartmentTreeNode[] => {
|
||||
const out: AdminDepartmentTreeNode[] = [];
|
||||
for (const n of nodes) {
|
||||
const children = filterTree(n.children || []);
|
||||
const haystack = [n.name, n.code, n.company, n.description]
|
||||
.filter(Boolean)
|
||||
.join(' ')
|
||||
.toLowerCase();
|
||||
if (!q || haystack.includes(q) || children.length) {
|
||||
out.push({ ...n, children });
|
||||
}
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
const activeTree = q ? filterTree(tree.value) : tree.value;
|
||||
const rows: DeptTreeDisplayRow[] = [];
|
||||
|
||||
/** 递归铺开部门行;搜索态全展开,常态按 expandedIds */
|
||||
const appendDeptRows = (nodes: AdminDepartmentTreeNode[], depth: number): void => {
|
||||
for (const n of nodes) {
|
||||
const children = n.children || [];
|
||||
const expanded = q ? true : expandedIds.value.has(n.id);
|
||||
rows.push({
|
||||
kind: 'dept',
|
||||
key: `dept:${n.id}`,
|
||||
depth,
|
||||
node: n,
|
||||
expanded,
|
||||
hasChildren: children.length > 0,
|
||||
totalMembers: n.total_member_count || 0,
|
||||
company: n.company,
|
||||
});
|
||||
if (expanded && children.length) appendDeptRows(children, depth + 1);
|
||||
}
|
||||
};
|
||||
|
||||
// 树顶公司虚拟分组:顶级部门按 company 文本归堆(未填公司归入「未分配公司」)
|
||||
const groups = new Map<string, AdminDepartmentTreeNode[]>();
|
||||
for (const root of activeTree) {
|
||||
const key = root.company?.trim() || '';
|
||||
if (!groups.has(key)) groups.set(key, []);
|
||||
groups.get(key)!.push(root);
|
||||
}
|
||||
const groupKeys = [...groups.keys()].sort((a, b) => a.localeCompare(b, 'zh-Hans-CN'));
|
||||
for (const key of groupKeys) {
|
||||
const roots = groups.get(key)!;
|
||||
const companyOpen = q ? true : expandedCompanies.value.has(key);
|
||||
rows.push({
|
||||
kind: 'company',
|
||||
key: `company:${key}`,
|
||||
depth: 0,
|
||||
company: key || t('admin.dept.noCompany'),
|
||||
expanded: companyOpen,
|
||||
hasChildren: true,
|
||||
totalMembers: roots.reduce((sum, r) => sum + (r.total_member_count || 0), 0),
|
||||
});
|
||||
if (companyOpen) appendDeptRows(roots, 1);
|
||||
}
|
||||
return rows;
|
||||
});
|
||||
|
||||
/** 在树中按 id 查找节点。 */
|
||||
const findNode = (
|
||||
nodes: AdminDepartmentTreeNode[],
|
||||
id: number,
|
||||
): AdminDepartmentTreeNode | null => {
|
||||
for (const n of nodes) {
|
||||
if (n.id === id) return n;
|
||||
const hit = findNode(n.children || [], id);
|
||||
if (hit) return hit;
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
/** 在树中查找 id 的祖先路径(含自身,不含公司虚拟层)。 */
|
||||
const findPath = (nodes: AdminDepartmentTreeNode[], id: number, trail: AdminDepartmentTreeNode[] = []): AdminDepartmentTreeNode[] | null => {
|
||||
for (const n of nodes) {
|
||||
const next = [...trail, n];
|
||||
if (n.id === id) return next;
|
||||
const hit = findPath(n.children || [], id, next);
|
||||
if (hit) return hit;
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
// ---------- 右侧成员面板(OA 组织结构口径:点部门出成员列表) ----------
|
||||
const selectedDeptId = ref<number | null>(null);
|
||||
const memberData = ref<AdminDepartmentMembersResponse | null>(null);
|
||||
const memberLoading = ref(false);
|
||||
const memberKeyword = ref('');
|
||||
const memberIncludeDescendants = ref(true);
|
||||
const memberPage = ref(1);
|
||||
const memberPageSize = ref(20);
|
||||
// 竞态保护:仅采纳最后一次请求的结果(切部门/翻页/搜索连击时旧响应作废)
|
||||
let memberRequestSeq = 0;
|
||||
let memberKeywordTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
const MEMBER_KEYWORD_DEBOUNCE_MS = 300;
|
||||
|
||||
const selectedDept = computed<AdminDepartmentTreeNode | null>(() =>
|
||||
selectedDeptId.value ? findNode(tree.value, selectedDeptId.value) : null,
|
||||
);
|
||||
|
||||
/** 选中部门的祖先路径(面包屑:公司分组名 → … → 本部门)。 */
|
||||
const selectedDeptPath = computed<string[]>(() => {
|
||||
if (!selectedDeptId.value) return [];
|
||||
const path = findPath(tree.value, selectedDeptId.value) || [];
|
||||
const rootCompany = path[0]?.company?.trim() || t('admin.dept.noCompany');
|
||||
return [rootCompany, ...path.map((n) => n.name)];
|
||||
});
|
||||
|
||||
/** 拉取当前选中部门的分页成员名单。 */
|
||||
const fetchMembers = async (): Promise<void> => {
|
||||
if (!selectedDeptId.value) {
|
||||
memberData.value = null;
|
||||
return;
|
||||
}
|
||||
const seq = ++memberRequestSeq;
|
||||
memberLoading.value = true;
|
||||
try {
|
||||
const data = (await listAdminDepartmentMembers(selectedDeptId.value, {
|
||||
includeDescendants: memberIncludeDescendants.value,
|
||||
keyword: memberKeyword.value,
|
||||
page: memberPage.value,
|
||||
pageSize: memberPageSize.value,
|
||||
})) as AdminDepartmentMembersResponse;
|
||||
if (seq === memberRequestSeq) memberData.value = data;
|
||||
} catch (e) {
|
||||
console.error('Failed to load department members', e);
|
||||
if (seq === memberRequestSeq) {
|
||||
memberData.value = null;
|
||||
msg.error((e as Error).message || t('admin.msg.requestFailed'));
|
||||
}
|
||||
} finally {
|
||||
if (seq === memberRequestSeq) memberLoading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 选中树节点:右侧面板加载该部门成员。
|
||||
* @param node - 被点击的部门节点
|
||||
*/
|
||||
const selectDept = (node: AdminDepartmentTreeNode): void => {
|
||||
if (selectedDeptId.value === node.id) return;
|
||||
selectedDeptId.value = node.id;
|
||||
memberKeyword.value = '';
|
||||
memberPage.value = 1;
|
||||
void fetchMembers();
|
||||
};
|
||||
|
||||
/** 成员关键词输入(300ms 防抖后回到第 1 页重新查询)。 */
|
||||
const setMemberKeyword = (value: string): void => {
|
||||
memberKeyword.value = value;
|
||||
if (memberKeywordTimer) clearTimeout(memberKeywordTimer);
|
||||
memberKeywordTimer = setTimeout(() => {
|
||||
memberKeywordTimer = null;
|
||||
memberPage.value = 1;
|
||||
void fetchMembers();
|
||||
}, MEMBER_KEYWORD_DEBOUNCE_MS);
|
||||
};
|
||||
|
||||
/** 切换「含下级部门」口径:回到第 1 页重新查询。 */
|
||||
const setMemberIncludeDescendants = (value: boolean): void => {
|
||||
memberIncludeDescendants.value = value;
|
||||
memberPage.value = 1;
|
||||
void fetchMembers();
|
||||
};
|
||||
|
||||
/** 翻页 / 调整每页条数。 */
|
||||
const setMemberPage = (page: number): void => {
|
||||
memberPage.value = Math.max(page, 1);
|
||||
void fetchMembers();
|
||||
};
|
||||
const setMemberPageSize = (size: number): void => {
|
||||
memberPageSize.value = size;
|
||||
memberPage.value = 1;
|
||||
void fetchMembers();
|
||||
};
|
||||
|
||||
/** 选中部门被删除或树刷新后,校正成员面板状态。 */
|
||||
const syncMemberPanelAfterTreeReload = (deletedId?: number): void => {
|
||||
if (deletedId != null && deletedId === selectedDeptId.value) {
|
||||
selectedDeptId.value = null;
|
||||
memberData.value = null;
|
||||
return;
|
||||
}
|
||||
if (selectedDeptId.value) void fetchMembers();
|
||||
};
|
||||
|
||||
/** 表单弹窗「上级部门」选项:编辑时排除自身及子孙,避免把子树挂到自己下面 */
|
||||
const parentOptions = computed<DeptParentOption[]>(() => {
|
||||
const options: DeptParentOption[] = [
|
||||
{ id: null, label: t('admin.dept.fields.parentRoot'), disabled: false },
|
||||
];
|
||||
const exclude = new Set<number>();
|
||||
if (form.value.id) {
|
||||
const stack: number[] = [form.value.id];
|
||||
const target = findNode(tree.value, form.value.id);
|
||||
const collect = (nodes: AdminDepartmentTreeNode[]): void => {
|
||||
for (const n of nodes) {
|
||||
stack.push(n.id);
|
||||
collect(n.children || []);
|
||||
}
|
||||
};
|
||||
if (target) collect(target.children || []);
|
||||
while (stack.length) exclude.add(stack.pop()!);
|
||||
}
|
||||
const walk = (nodes: AdminDepartmentTreeNode[], depth: number): void => {
|
||||
for (const n of nodes) {
|
||||
options.push({
|
||||
id: n.id,
|
||||
label: `${' '.repeat(depth)}${n.name}`,
|
||||
disabled: exclude.has(n.id),
|
||||
});
|
||||
walk(n.children || [], depth + 1);
|
||||
}
|
||||
};
|
||||
walk(tree.value, 0);
|
||||
return options;
|
||||
});
|
||||
|
||||
/**
|
||||
* 页面初始化:加载部门树并结束 loading。
|
||||
* @returns Promise<void>
|
||||
*/
|
||||
const loadAll = async (): Promise<void> => {
|
||||
@@ -96,32 +323,59 @@ export function useDepartmentsAdmin() {
|
||||
isLoading.value = false;
|
||||
};
|
||||
|
||||
/**
|
||||
* 把 Element 表头排序写回本地排序状态。
|
||||
* 核心逻辑:第三次点击清空排序时回到接口原顺序;有效列只排当前过滤结果,不请求接口。
|
||||
* @param key - 名称、编码、公司;空字符串表示取消排序
|
||||
* @param dir - asc、desc,或空
|
||||
*/
|
||||
const applySort = (key: DeptSortKey | '', dir: SortDir | ''): void => {
|
||||
if (key === '' || dir === '') {
|
||||
sortKey.value = undefined;
|
||||
return;
|
||||
}
|
||||
sortKey.value = key;
|
||||
sortDir.value = dir;
|
||||
/** 切换部门节点展开/收起。 */
|
||||
const toggleNode = (id: number): void => {
|
||||
const next = new Set(expandedIds.value);
|
||||
if (next.has(id)) next.delete(id);
|
||||
else next.add(id);
|
||||
expandedIds.value = next;
|
||||
};
|
||||
|
||||
/** 打开「添加部门」弹窗并重置表单。 */
|
||||
const openCreateModal = (): void => {
|
||||
/** 切换公司虚拟分组展开/收起。 */
|
||||
const toggleCompany = (key: string): void => {
|
||||
const next = new Set(expandedCompanies.value);
|
||||
if (next.has(key)) next.delete(key);
|
||||
else next.add(key);
|
||||
expandedCompanies.value = next;
|
||||
};
|
||||
|
||||
/** 全部展开(含所有公司组与部门节点)。 */
|
||||
const expandAll = (): void => {
|
||||
const ids = new Set<number>();
|
||||
const walk = (nodes: AdminDepartmentTreeNode[]): void => {
|
||||
for (const n of nodes) {
|
||||
ids.add(n.id);
|
||||
walk(n.children || []);
|
||||
}
|
||||
};
|
||||
walk(tree.value);
|
||||
expandedIds.value = ids;
|
||||
expandedCompanies.value = new Set(tree.value.map((r) => r.company?.trim() || ''));
|
||||
};
|
||||
|
||||
/** 全部收起(仅保留公司组层)。 */
|
||||
const collapseAll = (): void => {
|
||||
expandedIds.value = new Set();
|
||||
expandedCompanies.value = new Set();
|
||||
};
|
||||
|
||||
/**
|
||||
* 打开「添加部门」弹窗。
|
||||
* @param parent - 上级部门节点(添加子部门时传入);空 = 顶级
|
||||
* @param company - 预填公司(公司虚拟分组行的「添加子部门」传入)
|
||||
*/
|
||||
const openCreateModal = (parent?: AdminDepartmentTreeNode | null, company?: string): void => {
|
||||
form.value = createEmptyDepartmentForm();
|
||||
form.value.parentId = parent ? parent.id : null;
|
||||
form.value.company = company ?? parent?.company ?? '';
|
||||
showFormModal.value = true;
|
||||
};
|
||||
|
||||
/**
|
||||
* 打开「编辑部门」弹窗并回填选中行数据。
|
||||
* @param dept - 待编辑的部门行
|
||||
* @param dept - 待编辑的部门树节点
|
||||
*/
|
||||
const openEditModal = (dept: AdminDepartmentRow): void => {
|
||||
const openEditModal = (dept: AdminDepartmentTreeNode): void => {
|
||||
form.value = departmentRowToForm(dept);
|
||||
showFormModal.value = true;
|
||||
};
|
||||
@@ -134,7 +388,8 @@ export function useDepartmentsAdmin() {
|
||||
|
||||
/**
|
||||
* 保存部门:有 id 则更新,否则新建。
|
||||
* 核心逻辑:校验名称 → 调 create/update API → 刷新列表并关闭弹窗。
|
||||
* 核心逻辑:校验名称 → 组装含 parent_id/sort_order/is_hidden 的载荷 → 调 API → 刷新树并关闭弹窗。
|
||||
* 后端负责同级查重、防成环等校验,失败抛 BusinessError(errors.json 四语言文案)。
|
||||
* @returns Promise<void>
|
||||
*/
|
||||
const saveDepartment = async (): Promise<void> => {
|
||||
@@ -149,6 +404,9 @@ export function useDepartmentsAdmin() {
|
||||
code: form.value.code?.trim() || '',
|
||||
company: form.value.company?.trim() || '',
|
||||
description: form.value.description?.trim() || '',
|
||||
parent_id: form.value.parentId ?? null,
|
||||
sort_order: form.value.sortOrder ?? 0,
|
||||
is_hidden: !!form.value.isHidden,
|
||||
};
|
||||
if (form.value.id) {
|
||||
await updateAdminDepartment(form.value.id, payload);
|
||||
@@ -157,6 +415,7 @@ export function useDepartmentsAdmin() {
|
||||
}
|
||||
closeFormModal();
|
||||
await loadDepartments();
|
||||
syncMemberPanelAfterTreeReload();
|
||||
} catch (e) {
|
||||
msg.error((e as Error).message || t('admin.msg.failed'));
|
||||
} finally {
|
||||
@@ -165,8 +424,8 @@ export function useDepartmentsAdmin() {
|
||||
};
|
||||
|
||||
/**
|
||||
* 删除指定部门。先用 Element 确认框询问,取消则不请求。
|
||||
* 核心逻辑:MessageBox 在取消时 reject,这里吞掉;确定后再调删除接口并刷新列表。
|
||||
* 删除指定部门:ElMessageBox 确认后调接口。
|
||||
* 有下级部门或名下仍有员工时后端返回 409(HAS_CHILDREN / HAS_MEMBERS),此处展示其文案。
|
||||
* @param id - 部门主键
|
||||
*/
|
||||
const deleteDepartment = async (id: number): Promise<void> => {
|
||||
@@ -182,6 +441,7 @@ export function useDepartmentsAdmin() {
|
||||
try {
|
||||
await deleteAdminDepartment(id);
|
||||
await loadDepartments();
|
||||
syncMemberPanelAfterTreeReload(id);
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
msg.error((e as Error).message || t('admin.msg.requestFailed'));
|
||||
@@ -189,22 +449,38 @@ export function useDepartmentsAdmin() {
|
||||
};
|
||||
|
||||
return {
|
||||
departments,
|
||||
filteredDepartments,
|
||||
tree,
|
||||
displayRows,
|
||||
parentOptions,
|
||||
form,
|
||||
searchQuery,
|
||||
sortKey,
|
||||
sortDir,
|
||||
isLoading,
|
||||
isListLoading,
|
||||
isSaving,
|
||||
showFormModal,
|
||||
loadAll,
|
||||
applySort,
|
||||
toggleNode,
|
||||
toggleCompany,
|
||||
expandAll,
|
||||
collapseAll,
|
||||
openCreateModal,
|
||||
openEditModal,
|
||||
closeFormModal,
|
||||
saveDepartment,
|
||||
deleteDepartment,
|
||||
// 成员面板(OA 口径:左树右成员列表)
|
||||
selectedDeptId,
|
||||
selectedDept,
|
||||
selectedDeptPath,
|
||||
memberData,
|
||||
memberLoading,
|
||||
memberKeyword,
|
||||
memberIncludeDescendants,
|
||||
memberPage,
|
||||
memberPageSize,
|
||||
selectDept,
|
||||
setMemberKeyword,
|
||||
setMemberIncludeDescendants,
|
||||
setMemberPage,
|
||||
setMemberPageSize,
|
||||
};
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
@@ -76,21 +76,40 @@ export interface AdminDepartmentRow {
|
||||
code?: string;
|
||||
company?: string;
|
||||
description?: string;
|
||||
/** 上级部门主键;null/缺省表示顶级部门 */
|
||||
parent_id?: number | null;
|
||||
/** 同级排序号(升序),对应 ERP hrao09 */
|
||||
sort_order?: number;
|
||||
/** 是否在组织树中隐藏(对应 ERP hrao08;管理端仍可见并打标) */
|
||||
is_hidden?: boolean;
|
||||
member_count?: number;
|
||||
}
|
||||
|
||||
/** 部门树节点:/admin/departments/tree 返回结构,children 已按同级排序号排好 */
|
||||
export interface AdminDepartmentTreeNode extends AdminDepartmentRow {
|
||||
/** 含全部下级部门的成员总数(递归汇总) */
|
||||
total_member_count?: number;
|
||||
children: AdminDepartmentTreeNode[];
|
||||
}
|
||||
|
||||
export interface AdminDepartmentMember {
|
||||
id: number;
|
||||
username: string;
|
||||
real_name?: string;
|
||||
employee_id?: string;
|
||||
email?: string;
|
||||
phone_number?: string;
|
||||
/** 成员所属部门名(含下级视图下用于区分来源部门) */
|
||||
department?: string;
|
||||
status?: string;
|
||||
}
|
||||
|
||||
/** 部门成员分页响应(OA 组织面板口径:右侧成员列表) */
|
||||
export interface AdminDepartmentMembersResponse {
|
||||
department: AdminDepartmentRow;
|
||||
count: number;
|
||||
total: number;
|
||||
page: number;
|
||||
page_size: number;
|
||||
members: AdminDepartmentMember[];
|
||||
}
|
||||
|
||||
|
||||
@@ -12,6 +12,12 @@ export interface DepartmentFormState {
|
||||
code?: string;
|
||||
company?: string;
|
||||
description?: string;
|
||||
/** 上级部门主键;null 表示顶级部门 */
|
||||
parentId?: number | null;
|
||||
/** 同级排序号(升序) */
|
||||
sortOrder?: number;
|
||||
/** 是否在组织树中隐藏 */
|
||||
isHidden?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -23,6 +29,9 @@ export const createEmptyDepartmentForm = (): DepartmentFormState => ({
|
||||
code: '',
|
||||
company: '',
|
||||
description: '',
|
||||
parentId: null,
|
||||
sortOrder: 0,
|
||||
isHidden: false,
|
||||
});
|
||||
|
||||
/**
|
||||
@@ -36,4 +45,7 @@ export const departmentRowToForm = (dept: AdminDepartmentRow): DepartmentFormSta
|
||||
code: dept.code || '',
|
||||
company: dept.company || '',
|
||||
description: dept.description || '',
|
||||
parentId: dept.parent_id ?? null,
|
||||
sortOrder: dept.sort_order ?? 0,
|
||||
isHidden: !!dept.is_hidden,
|
||||
});
|
||||
@@ -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"
|
||||
|
||||
@@ -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('反馈提交成功')"
|
||||
/>
|
||||
|
||||
@@ -1292,6 +1292,12 @@
|
||||
"subtitle": "Manage organization structure",
|
||||
"edit": "Edit Department",
|
||||
"add": "Add New Department",
|
||||
"addChild": "Add sub-department",
|
||||
"expandAll": "Expand all",
|
||||
"collapseAll": "Collapse all",
|
||||
"expand": "Expand",
|
||||
"collapse": "Collapse",
|
||||
"noCompany": "Unassigned company",
|
||||
"noDepts": "No departments configured.",
|
||||
"noSearchResults": "No matching departments found",
|
||||
"searchPlaceholder": "Search by name, code, or company…",
|
||||
@@ -1304,14 +1310,30 @@
|
||||
},
|
||||
"actions": {
|
||||
"edit": "Edit",
|
||||
"delete": "Delete",
|
||||
"viewMembers": "View department members"
|
||||
"delete": "Delete"
|
||||
},
|
||||
"members": {
|
||||
"title": "{name} Members",
|
||||
"count": "{count} members",
|
||||
"empty": "No members"
|
||||
"empty": "No members in this department",
|
||||
"includeDescendants": "Include sub-departments",
|
||||
"searchPlaceholder": "Search name / employee ID / email / phone",
|
||||
"total": "{total} people in total",
|
||||
"hint": "Click a department on the left to view its members",
|
||||
"prevPage": "Previous page",
|
||||
"nextPage": "Next page",
|
||||
"columns": {
|
||||
"name": "Name",
|
||||
"contact": "Contact",
|
||||
"employeeId": "Employee ID",
|
||||
"department": "Department",
|
||||
"status": "Status"
|
||||
},
|
||||
"status": {
|
||||
"active": "Active",
|
||||
"pending": "Pending",
|
||||
"rejected": "Rejected"
|
||||
}
|
||||
},
|
||||
"tags": { "hidden": "Hidden" },
|
||||
"fields": {
|
||||
"name": "Name",
|
||||
"namePlaceholder": "e.g. IT Department",
|
||||
@@ -1320,6 +1342,12 @@
|
||||
"company": "Company",
|
||||
"companyPlaceholder": "e.g. HQ",
|
||||
"description": "Description",
|
||||
"parent": "Parent department",
|
||||
"parentRoot": "(As top-level department)",
|
||||
"sort": "Sibling order",
|
||||
"visibility": "Visibility",
|
||||
"hidden": "Hide in organization tree",
|
||||
"hiddenHint": "Hidden departments are excluded from the organization tree but remain visible here (maps to ERP \"show in org chart\")",
|
||||
"descriptionPlaceholder": "Department description..."
|
||||
},
|
||||
"confirmDelete": "Delete this department?",
|
||||
@@ -2369,6 +2397,7 @@
|
||||
"markClosed": "Mark closed",
|
||||
"closed": "Closed",
|
||||
"closedOk": "Marked as closed",
|
||||
"closePreview": "Close preview",
|
||||
"summary": {
|
||||
"pending": "Pending",
|
||||
"pendingHint": "Feedback to follow up",
|
||||
|
||||
@@ -298,6 +298,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.",
|
||||
@@ -619,6 +622,13 @@
|
||||
"INTEGRATION.BINDING_LEGACY_PUT_REJECTED": "Legacy single-step fields would truncate this binding's multi-step recipe; submit ordered steps via steps_json instead.",
|
||||
"INTEGRATION.CALL_NOT_FOUND": "Integration call not found.",
|
||||
"INTEGRATION.BINDING_STEPS_INVALID": "Binding steps invalid: steps_json is required, must be a non-empty array of objects.",
|
||||
"DEPT.NAME_REQUIRED": "Department name is required.",
|
||||
"DEPT.PARENT_INVALID": "Parent department does not exist or has been deleted.",
|
||||
"DEPT.NAME_EXISTS": "A sibling department with the same name already exists.",
|
||||
"DEPT.CODE_EXISTS": "Department code is already used by another department.",
|
||||
"DEPT.CYCLE_FORBIDDEN": "A department cannot be its own parent or descendant.",
|
||||
"DEPT.HAS_CHILDREN": "This department has child departments; move or delete them first.",
|
||||
"DEPT.HAS_MEMBERS": "This department still has members and cannot be deleted.",
|
||||
"SHIPPING.CUSTOMER_REBIND_BLOCKED": "Customer cannot be changed after a shipping notice/Excel has been generated — undo it first",
|
||||
"SHIPPING.CUSTOMER_REBIND_SAME_CUSTOMER": "The selected customer is already the confirmed customer",
|
||||
"SHIPPING.CUSTOMER_RESOLUTION_REQUIRED": "Confirm the customer identification first",
|
||||
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
@@ -1292,6 +1292,12 @@
|
||||
"subtitle": "จัดการโครงสร้างองค์กร",
|
||||
"edit": "แก้ไขแผนก",
|
||||
"add": "เพิ่มแผนกใหม่",
|
||||
"addChild": "เพิ่มแผนกย่อย",
|
||||
"expandAll": "ขยายทั้งหมด",
|
||||
"collapseAll": "ยุบทั้งหมด",
|
||||
"expand": "ขยาย",
|
||||
"collapse": "ยุบ",
|
||||
"noCompany": "ยังไม่ระบุบริษัท",
|
||||
"noDepts": "ยังไม่มีการกำหนดค่าแผนก",
|
||||
"noSearchResults": "ไม่พบแผนกที่ตรงกัน",
|
||||
"searchPlaceholder": "ค้นหาชื่อ รหัส หรือบริษัท…",
|
||||
@@ -1304,9 +1310,9 @@
|
||||
},
|
||||
"actions": {
|
||||
"edit": "แก้ไข",
|
||||
"delete": "ลบ",
|
||||
"viewMembers": "View department members"
|
||||
"delete": "ลบ"
|
||||
},
|
||||
"tags": { "hidden": "ซ่อนอยู่" },
|
||||
"fields": {
|
||||
"name": "ชื่อ",
|
||||
"namePlaceholder": "เช่น แผนกไอที",
|
||||
@@ -1315,6 +1321,12 @@
|
||||
"company": "บริษัท",
|
||||
"companyPlaceholder": "เช่น สำนักงานใหญ่",
|
||||
"description": "คำอธิบาย",
|
||||
"parent": "แผนกแม่",
|
||||
"parentRoot": "(เป็นแผนกระดับบนสุด)",
|
||||
"sort": "ลำดับภายในระดับเดียวกัน",
|
||||
"visibility": "การแสดงผล",
|
||||
"hidden": "ซ่อนในผังองค์กร",
|
||||
"hiddenHint": "ซ่อนจากผังองค์กรแต่ผู้ดูแลระบบยังมองเห็น (ตรงกับ ERP \"แสดงในผังองค์กรหรือไม่\")",
|
||||
"descriptionPlaceholder": "กรอกรายละเอียดแผนก..."
|
||||
},
|
||||
"confirmDelete": "ลบแผนกนี้หรือไม่?",
|
||||
@@ -1322,9 +1334,25 @@
|
||||
"nameRequired": "กรุณากรอกชื่อแผนก"
|
||||
},
|
||||
"members": {
|
||||
"title": "{name} Members",
|
||||
"count": "{count} members",
|
||||
"empty": "No members"
|
||||
"empty": "แผนกนี้ยังไม่มีพนักงาน",
|
||||
"includeDescendants": "รวมแผนกย่อย",
|
||||
"searchPlaceholder": "ค้นหาชื่อ / รหัสพนักงาน / อีเมล / โทรศัพท์",
|
||||
"total": "รวม {total} คน",
|
||||
"hint": "คลิกแผนกด้านซ้ายเพื่อดูพนักงาน",
|
||||
"prevPage": "หน้าก่อนหน้า",
|
||||
"nextPage": "หน้าถัดไป",
|
||||
"columns": {
|
||||
"name": "ชื่อ",
|
||||
"contact": "ช่องทางติดต่อ",
|
||||
"employeeId": "รหัสพนักงาน",
|
||||
"department": "แผนก",
|
||||
"status": "สถานะ"
|
||||
},
|
||||
"status": {
|
||||
"active": "ใช้งาน",
|
||||
"pending": "รออนุมัติ",
|
||||
"rejected": "ปฏิเสธ"
|
||||
}
|
||||
}
|
||||
},
|
||||
"agent": {
|
||||
@@ -2351,6 +2379,7 @@
|
||||
"markClosed": "ทำเครื่องหมายว่าปิดแล้ว",
|
||||
"closed": "ปิดแล้ว",
|
||||
"closedOk": "ทำเครื่องหมายว่าปิดแล้ว",
|
||||
"closePreview": "ปิดตัวอย่าง",
|
||||
"summary": {
|
||||
"pending": "รอดำเนินการ",
|
||||
"pendingHint": "ข้อเสนอแนะรอติดตาม",
|
||||
|
||||
@@ -298,6 +298,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": "ไฟล์ถูกอ้างอิงโดยธุรกิจแล้ว ไม่สามารถลบได้",
|
||||
@@ -619,6 +622,13 @@
|
||||
"INTEGRATION.BINDING_LEGACY_PUT_REJECTED": "ฟิลด์ขั้นตอนเดียวแบบเดิมจะตัดทอนสูตรหลายขั้นตอนของการผูกนี้ โปรดส่งขั้นตอนตามลำดับด้วย steps_json แทน",
|
||||
"INTEGRATION.CALL_NOT_FOUND": "ไม่พบระเบียนการเรียกใช้งานการผสานรวม",
|
||||
"INTEGRATION.BINDING_STEPS_INVALID": "การกำหนดค่าขั้นตอนการเชื่อมโยงไม่ถูกต้อง: steps_json จำเป็นต้องมีและเป็นอาร์เรย์ที่ไม่ว่าง โดยแต่ละรายการต้องเป็นออบเจกต์",
|
||||
"DEPT.NAME_REQUIRED": "กรุณากรอกชื่อแผนก",
|
||||
"DEPT.PARENT_INVALID": "ไม่พบแผนกแม่หรือแผนกแม่ถูกลบแล้ว",
|
||||
"DEPT.NAME_EXISTS": "มีแผนกชื่อเดียวกันอยู่ภายใต้แผนกแม่เดียวกันแล้ว",
|
||||
"DEPT.CODE_EXISTS": "รหัสแผนกนี้ถูกใช้โดยแผนกอื่นแล้ว",
|
||||
"DEPT.CYCLE_FORBIDDEN": "แผนกไม่สามารถเป็นแผนกแม่ของตัวเองหรือแผนกย่อยของตัวเองได้",
|
||||
"DEPT.HAS_CHILDREN": "แผนกนี้มีแผนกย่อย กรุณาจัดการแผนกย่อยก่อนจึงจะลบได้",
|
||||
"DEPT.HAS_MEMBERS": "แผนกนี้ยังมีพนักงานอยู่ จึงไม่สามารถลบได้",
|
||||
"SHIPPING.CUSTOMER_REBIND_BLOCKED": "มีการแจ้งเตือน/Excel แล้ว ไม่สามารถเปลี่ยนลูกค้าได้ โปรดยกเลิกก่อน",
|
||||
"SHIPPING.CUSTOMER_REBIND_SAME_CUSTOMER": "ลูกค้าที่เลือกเป็นลูกค้าที่ยืนยันอยู่แล้ว",
|
||||
"SHIPPING.CUSTOMER_RESOLUTION_REQUIRED": "โปรดยืนยันการระบุลูกค้าก่อน",
|
||||
|
||||
@@ -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": "นำรูปภาพออก"
|
||||
}
|
||||
}
|
||||
@@ -1423,6 +1423,12 @@
|
||||
"subtitle": "管理组织架构",
|
||||
"edit": "编辑部门",
|
||||
"add": "添加部门",
|
||||
"addChild": "添加子部门",
|
||||
"expandAll": "全部展开",
|
||||
"collapseAll": "全部收起",
|
||||
"expand": "展开",
|
||||
"collapse": "收起",
|
||||
"noCompany": "未分配公司",
|
||||
"noDepts": "暂无部门配置",
|
||||
"noSearchResults": "未找到匹配的部门",
|
||||
"searchPlaceholder": "搜索名称、编码或公司…",
|
||||
@@ -1435,14 +1441,30 @@
|
||||
},
|
||||
"actions": {
|
||||
"edit": "编辑",
|
||||
"delete": "删除",
|
||||
"viewMembers": "查看部门员工"
|
||||
"delete": "删除"
|
||||
},
|
||||
"members": {
|
||||
"title": "{name}员工",
|
||||
"count": "共 {count} 人",
|
||||
"empty": "暂无员工"
|
||||
"empty": "该部门暂无员工",
|
||||
"includeDescendants": "含下级部门",
|
||||
"searchPlaceholder": "搜索姓名 / 工号 / 邮箱 / 手机",
|
||||
"total": "共 {total} 人",
|
||||
"hint": "点击左侧部门查看员工",
|
||||
"prevPage": "上一页",
|
||||
"nextPage": "下一页",
|
||||
"columns": {
|
||||
"name": "姓名",
|
||||
"contact": "联系方式",
|
||||
"employeeId": "工号",
|
||||
"department": "部门",
|
||||
"status": "状态"
|
||||
},
|
||||
"status": {
|
||||
"active": "启用",
|
||||
"pending": "待审核",
|
||||
"rejected": "已拒绝"
|
||||
}
|
||||
},
|
||||
"tags": { "hidden": "已隐藏" },
|
||||
"fields": {
|
||||
"name": "名称",
|
||||
"namePlaceholder": "例如:信息技术部",
|
||||
@@ -1451,6 +1473,12 @@
|
||||
"company": "公司",
|
||||
"companyPlaceholder": "例如:总部",
|
||||
"description": "描述",
|
||||
"parent": "上级部门",
|
||||
"parentRoot": "(作为顶级部门)",
|
||||
"sort": "同级排序",
|
||||
"visibility": "显示设置",
|
||||
"hidden": "在组织树中隐藏",
|
||||
"hiddenHint": "隐藏后不在组织树中展示,管理端仍可见(对应 ERP「在组织框架图中显示否」)",
|
||||
"descriptionPlaceholder": "请输入部门描述..."
|
||||
},
|
||||
"confirmDelete": "确定删除该部门吗?",
|
||||
@@ -2482,6 +2510,7 @@
|
||||
"markClosed": "标记已关闭",
|
||||
"closed": "已关闭",
|
||||
"closedOk": "已标记关闭",
|
||||
"closePreview": "关闭预览",
|
||||
"summary": {
|
||||
"pending": "待处理",
|
||||
"pendingHint": "待跟进反馈",
|
||||
|
||||
@@ -298,6 +298,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": "文件已被业务引用,无法删除。",
|
||||
@@ -619,6 +622,13 @@
|
||||
"INTEGRATION.BINDING_LEGACY_PUT_REJECTED": "旧单步字段会截断该绑定的多步配方,请改用 steps_json 提交有序步骤。",
|
||||
"INTEGRATION.CALL_NOT_FOUND": "集成调用记录不存在。",
|
||||
"INTEGRATION.BINDING_STEPS_INVALID": "绑定步骤配置不合法:steps_json 必填且为非空数组,每项须为对象。",
|
||||
"DEPT.NAME_REQUIRED": "部门名称必填。",
|
||||
"DEPT.PARENT_INVALID": "上级部门不存在或已被删除。",
|
||||
"DEPT.NAME_EXISTS": "同一上级部门下已存在同名部门。",
|
||||
"DEPT.CODE_EXISTS": "部门编码已被其他部门使用。",
|
||||
"DEPT.CYCLE_FORBIDDEN": "上级部门不能选择自己或自己的下级部门。",
|
||||
"DEPT.HAS_CHILDREN": "该部门存在下级部门,请先处理下级部门后再删除。",
|
||||
"DEPT.HAS_MEMBERS": "该部门名下仍有员工,无法删除。",
|
||||
"SHIPPING.CUSTOMER_REBIND_BLOCKED": "已产生发货通知/Excel,无法修改客户,请先走撤销流程",
|
||||
"SHIPPING.CUSTOMER_REBIND_SAME_CUSTOMER": "新客户与当前确认客户相同",
|
||||
"SHIPPING.CUSTOMER_RESOLUTION_REQUIRED": "请先完成客户识别确认",
|
||||
|
||||
@@ -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": "移除图片"
|
||||
}
|
||||
}
|
||||
@@ -1292,6 +1292,12 @@
|
||||
"subtitle": "管理組織架構",
|
||||
"edit": "編輯部門",
|
||||
"add": "添加部門",
|
||||
"addChild": "添加子部門",
|
||||
"expandAll": "全部展開",
|
||||
"collapseAll": "全部收起",
|
||||
"expand": "展開",
|
||||
"collapse": "收起",
|
||||
"noCompany": "未分配公司",
|
||||
"noDepts": "暫無部門配置",
|
||||
"noSearchResults": "未找到匹配的部門",
|
||||
"searchPlaceholder": "搜尋名稱、編碼或公司…",
|
||||
@@ -1304,9 +1310,9 @@
|
||||
},
|
||||
"actions": {
|
||||
"edit": "編輯",
|
||||
"delete": "刪除",
|
||||
"viewMembers": "View department members"
|
||||
"delete": "刪除"
|
||||
},
|
||||
"tags": { "hidden": "已隱藏" },
|
||||
"fields": {
|
||||
"name": "名稱",
|
||||
"namePlaceholder": "例如:資訊技術部",
|
||||
@@ -1315,6 +1321,12 @@
|
||||
"company": "公司",
|
||||
"companyPlaceholder": "例如:總部",
|
||||
"description": "描述",
|
||||
"parent": "上級部門",
|
||||
"parentRoot": "(作為頂級部門)",
|
||||
"sort": "同級排序",
|
||||
"visibility": "顯示設定",
|
||||
"hidden": "在組織樹中隱藏",
|
||||
"hiddenHint": "隱藏後不在組織樹中展示,管理端仍可見(對應 ERP「在組織框架圖中顯示否」)",
|
||||
"descriptionPlaceholder": "請輸入部門描述..."
|
||||
},
|
||||
"confirmDelete": "確定刪除該部門嗎?",
|
||||
@@ -1322,9 +1334,25 @@
|
||||
"nameRequired": "部門名稱必填"
|
||||
},
|
||||
"members": {
|
||||
"title": "{name} Members",
|
||||
"count": "{count} members",
|
||||
"empty": "No members"
|
||||
"empty": "該部門暫無員工",
|
||||
"includeDescendants": "含下級部門",
|
||||
"searchPlaceholder": "搜尋姓名 / 工號 / 郵箱 / 手機",
|
||||
"total": "共 {total} 人",
|
||||
"hint": "點擊左側部門查看員工",
|
||||
"prevPage": "上一頁",
|
||||
"nextPage": "下一頁",
|
||||
"columns": {
|
||||
"name": "姓名",
|
||||
"contact": "聯絡方式",
|
||||
"employeeId": "工號",
|
||||
"department": "部門",
|
||||
"status": "狀態"
|
||||
},
|
||||
"status": {
|
||||
"active": "啟用",
|
||||
"pending": "待審核",
|
||||
"rejected": "已拒絕"
|
||||
}
|
||||
}
|
||||
},
|
||||
"agent": {
|
||||
@@ -2351,6 +2379,7 @@
|
||||
"markClosed": "標記已關閉",
|
||||
"closed": "已關閉",
|
||||
"closedOk": "已標記關閉",
|
||||
"closePreview": "關閉預覽",
|
||||
"summary": {
|
||||
"pending": "待處理",
|
||||
"pendingHint": "待跟進反饋",
|
||||
|
||||
@@ -298,6 +298,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": "檔案已被業務引用,無法刪除。",
|
||||
@@ -619,6 +622,13 @@
|
||||
"INTEGRATION.BINDING_LEGACY_PUT_REJECTED": "舊單步欄位會截斷該繫結的多步配方,請改用 steps_json 提交有序步驟。",
|
||||
"INTEGRATION.CALL_NOT_FOUND": "整合調用記錄不存在。",
|
||||
"INTEGRATION.BINDING_STEPS_INVALID": "綁定步驟配置不合法:steps_json 必填且為非空陣列,每項須為物件。",
|
||||
"DEPT.NAME_REQUIRED": "部門名稱必填。",
|
||||
"DEPT.PARENT_INVALID": "上級部門不存在或已被刪除。",
|
||||
"DEPT.NAME_EXISTS": "同一上級部門下已存在同名部門。",
|
||||
"DEPT.CODE_EXISTS": "部門編碼已被其他部門使用。",
|
||||
"DEPT.CYCLE_FORBIDDEN": "上級部門不能選擇自己或自己的下級部門。",
|
||||
"DEPT.HAS_CHILDREN": "該部門存在下級部門,請先處理下級部門後再刪除。",
|
||||
"DEPT.HAS_MEMBERS": "該部門名下仍有員工,無法刪除。",
|
||||
"SHIPPING.CUSTOMER_REBIND_BLOCKED": "已產生發貨通知/Excel,無法修改客戶,請先走撤銷流程",
|
||||
"SHIPPING.CUSTOMER_REBIND_SAME_CUSTOMER": "新客戶與當前確認客戶相同",
|
||||
"SHIPPING.CUSTOMER_RESOLUTION_REQUIRED": "請先完成客戶識別確認",
|
||||
|
||||
@@ -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>
|
||||
@@ -6,6 +6,9 @@ import vue from '@vitejs/plugin-vue'
|
||||
const rootDir = path.dirname(fileURLToPath(import.meta.url))
|
||||
const frontendPort = Number(process.env.HXOPS_FRONTEND_PORT || '8881')
|
||||
const apiProxyTarget = process.env.HXOPS_API_PROXY_TARGET || 'http://127.0.0.1:5052'
|
||||
// Windows 下杀软实时扫描/系统睡眠可能使文件事件丢失(表现为“改了不生效、刷新也拿旧代码”),
|
||||
// 设置 HXOPS_VITE_POLLING=1 改用轮询监听:不依赖系统文件事件,稳定但略耗 CPU,按机器自选
|
||||
const usePolling = process.env.HXOPS_VITE_POLLING === '1'
|
||||
|
||||
// https://vite.dev/config/
|
||||
export default defineConfig({
|
||||
@@ -18,6 +21,10 @@ export default defineConfig({
|
||||
server: {
|
||||
port: frontendPort, // 默认 8881,允许本地通过环境变量覆盖,避免与其它仓库冲突
|
||||
strictPort: true, // 端口被占用时直接失败,由 start_local.ps1 先释放旧进程
|
||||
watch: {
|
||||
usePolling,
|
||||
interval: 300
|
||||
},
|
||||
allowedHosts: ['hx.benl.cn'],
|
||||
proxy: {
|
||||
'/api': {
|
||||
|
||||
Reference in new issue
Block a user