Merge branch 'dev' into hugo-shipping-notice

This commit is contained in:
hugo committed 2026-07-13 08:25:34 +08:00
commit a31735b689
47 files changed
+1931 -716

No files matched your search

-2
View File
@@ -22,8 +22,6 @@ AUTH_JWT_AUDIENCE=758be5fcba2df784fdb4
AUTH_JWT_JWKS_URL=http://192.168.100.192:8870/.well-known/jwks AUTH_JWT_JWKS_URL=http://192.168.100.192:8870/.well-known/jwks
# Casdoor # Casdoor
# 共用 IdP(可与生产 Casdoor 同机)
CASDOOR_BASE_URL=http://192.168.100.192:8870 CASDOOR_BASE_URL=http://192.168.100.192:8870
# 以下为 hxops-dev 应用在 Casdoor 控制台里的 Client ID / Secret(勿与 prod 混用) # 以下为 hxops-dev 应用在 Casdoor 控制台里的 Client ID / Secret(勿与 prod 混用)
CASDOOR_CLIENT_ID=758be5fcba2df784fdb4 CASDOOR_CLIENT_ID=758be5fcba2df784fdb4
+1 -1
View File
@@ -32,7 +32,7 @@ CASDOOR_CLIENT_SECRET=522161bea5bb4f90b63f77c41dc26d223f1244ab
CASDOOR_REDIRECT_URI=https://ait.well-trust.com/casdoor-callback CASDOOR_REDIRECT_URI=https://ait.well-trust.com/casdoor-callback
CASDOOR_SCOPE=openid profile email CASDOOR_SCOPE=openid profile email
CASDOOR_ORGANIZATION=organization_HX CASDOOR_ORGANIZATION=organization_HX
# Casdoor Providers → wecom:Name 字段(截图即为 wecom);Organization=organization_HX,Sub type=Internal,Scope=snsapi_userinfo # Casdoor Providers → wecom:Name 字段;Organization=organization_HX,Sub type=Internal,Scope=snsapi_userinfo
CASDOOR_WECOM_PROVIDER_HINT=wecom CASDOOR_WECOM_PROVIDER_HINT=wecom
# 知识库 Dify 对接 # 知识库 Dify 对接
+9 -2
View File
@@ -19,7 +19,7 @@ def _query_params() -> dict[str, str]:
@admin_bp.route('/reports/usage', methods=['GET']) @admin_bp.route('/reports/usage', methods=['GET'])
@require_admin @require_admin
def usage_report(): def usage_report():
"""聊天使用分析报表。""" """聊天使用分析报表(支持时间范围 range=7d|30d|90d|180d|365d)。"""
try: try:
user_page = int(request.args.get('user_page', 1)) user_page = int(request.args.get('user_page', 1))
except (TypeError, ValueError): except (TypeError, ValueError):
@@ -28,7 +28,14 @@ def usage_report():
user_page_size = int(request.args.get('user_page_size', 10)) user_page_size = int(request.args.get('user_page_size', 10))
except (TypeError, ValueError): except (TypeError, ValueError):
user_page_size = 10 user_page_size = 10
return jsonify(report_service.build_usage_report(user_page=user_page, user_page_size=user_page_size)) range_key = request.args.get('range')
return jsonify(
report_service.build_usage_report(
user_page=user_page,
user_page_size=user_page_size,
range_key=range_key,
)
)
@admin_bp.route('/reports/feedback', methods=['GET']) @admin_bp.route('/reports/feedback', methods=['GET'])
+46 -4
View File
@@ -8,7 +8,7 @@ backend/app/services/admin/report_service.py
from __future__ import annotations from __future__ import annotations
import math import math
from datetime import datetime from datetime import datetime, timedelta
from typing import Any from typing import Any
from sqlalchemy import desc, func from sqlalchemy import desc, func
@@ -18,13 +18,53 @@ from app.models import Agent, ChatLog, Feedback, GeneralFeedback, User
USAGE_BY_USER_TOP_LIMIT = 50 USAGE_BY_USER_TOP_LIMIT = 50
# 使用分析时间范围:key → 回溯天数(与前端下拉选项一致)
USAGE_RANGE_DAYS = {
'7d': 7,
'30d': 30,
'90d': 90,
'180d': 180,
'365d': 365,
}
DEFAULT_USAGE_RANGE = '30d'
def build_usage_report(*, user_page: int, user_page_size: int) -> dict:
"""聊天使用分析报表。""" def resolve_usage_range_start(range_key: str | None) -> tuple[str, datetime]:
total = db.session.query(ChatLog).count() """
解析使用分析时间范围,返回规范化 key 与起始 UTC 时间。
Args:
range_key: 前端传入的 range(7d/30d/90d/180d/365d),非法值回退近一月。
Returns:
(normalized_key, since_utc)
"""
key = (range_key or DEFAULT_USAGE_RANGE).strip().lower()
days = USAGE_RANGE_DAYS.get(key)
if days is None:
key = DEFAULT_USAGE_RANGE
days = USAGE_RANGE_DAYS[key]
since = datetime.utcnow() - timedelta(days=days)
return key, since
def build_usage_report(*, user_page: int, user_page_size: int, range_key: str | None = None) -> dict:
"""
聊天使用分析报表(按应用 / 按用户),限定时间范围内的 ChatLog。
Args:
user_page: 按用户统计分页页码。
user_page_size: 每页条数(上限 USAGE_BY_USER_TOP_LIMIT)。
range_key: 时间范围 key,见 USAGE_RANGE_DAYS。
"""
normalized_range, since = resolve_usage_range_start(range_key)
base_filter = ChatLog.created_at >= since
total = db.session.query(ChatLog).filter(base_filter).count()
by_agent = ( by_agent = (
db.session.query(Agent.name, func.count(ChatLog.id)) db.session.query(Agent.name, func.count(ChatLog.id))
.join(ChatLog) .join(ChatLog)
.filter(base_filter)
.group_by(Agent.name) .group_by(Agent.name)
.order_by(desc(func.count(ChatLog.id)), Agent.name) .order_by(desc(func.count(ChatLog.id)), Agent.name)
.all() .all()
@@ -34,6 +74,7 @@ def build_usage_report(*, user_page: int, user_page_size: int) -> dict:
by_user_top = ( by_user_top = (
db.session.query(User.username, func.count(ChatLog.id)) db.session.query(User.username, func.count(ChatLog.id))
.join(ChatLog) .join(ChatLog)
.filter(base_filter)
.group_by(User.username) .group_by(User.username)
.order_by(desc(func.count(ChatLog.id)), User.username) .order_by(desc(func.count(ChatLog.id)), User.username)
.limit(USAGE_BY_USER_TOP_LIMIT) .limit(USAGE_BY_USER_TOP_LIMIT)
@@ -46,6 +87,7 @@ def build_usage_report(*, user_page: int, user_page_size: int) -> dict:
by_user_page = by_user_top[offset:offset + user_page_size] by_user_page = by_user_top[offset:offset + user_page_size]
return { return {
'total': total, 'total': total,
'range': normalized_range,
'by_user': [{'username': u, 'count': c} for u, c in by_user_page], 'by_user': [{'username': u, 'count': c} for u, c in by_user_page],
'by_agent': [{'agent': a, 'count': c} for a, c in by_agent], 'by_agent': [{'agent': a, 'count': c} for a, c in by_agent],
'user_total': user_total, 'user_total': user_total,
+31 -2
View File
@@ -104,10 +104,39 @@ def apply_users_filters(query, query_params: dict[str, str]):
return query return query
# 用户列表允许的排序列(与前端「用户 / 部门」表头对应)
USER_SORT_COLUMNS = {
'username': User.username,
'department': User.department,
}
def resolve_users_order_by(query_params: dict[str, str]):
"""
解析 sort_by / sort_dir,返回 order_by 列元组。
核心逻辑:仅允许 username、department;非法值回退按 id 升序;同值用 id 稳定次序。
Args:
query_params: 请求查询参数(含 sort_by、sort_dir)。
Returns:
可直接传入 Query.order_by(*...) 的列表达式元组。
"""
sort_by = (query_params.get('sort_by') or '').strip().lower()
sort_dir = (query_params.get('sort_dir') or 'asc').strip().lower()
column = USER_SORT_COLUMNS.get(sort_by)
if column is None:
return (User.id.asc(),)
primary = column.desc() if sort_dir == 'desc' else column.asc()
return (primary, User.id.asc())
def list_users(query_params: dict[str, str]) -> list[dict] | dict: def list_users(query_params: dict[str, str]) -> list[dict] | dict:
query = apply_users_filters(db.session.query(User), query_params) query = apply_users_filters(db.session.query(User), query_params)
order_by = resolve_users_order_by(query_params)
if 'page' not in query_params: if 'page' not in query_params:
users = query.options(joinedload(User.agents)).order_by(User.id.asc()).all() users = query.options(joinedload(User.agents)).order_by(*order_by).all()
return [serialize_admin_user(u) for u in users] return [serialize_admin_user(u) for u in users]
try: try:
@@ -128,7 +157,7 @@ def list_users(query_params: dict[str, str]) -> list[dict] | dict:
users = ( users = (
query.options(joinedload(User.agents)) query.options(joinedload(User.agents))
.order_by(User.id.asc()) .order_by(*order_by)
.offset((page - 1) * page_size) .offset((page - 1) * page_size)
.limit(page_size) .limit(page_size)
.all() .all()
+47 -4
View File
@@ -1,3 +1,11 @@
"""
edkb_system/controller.py
用途:edkb 单文件清洗编排(intake → loader → OCR → clean → export)。
依赖:edkb_system.skills.*、SystemConfig、common.is_figure_rich_handbook。
逻辑:由 knowledge_cleaning.edkb_adapter / CLI 调用;手册类跳过丢图并强制 OCR。
"""
from __future__ import annotations from __future__ import annotations
import json import json
@@ -30,7 +38,7 @@ from edkb_system.skills import (
quality_gate, quality_gate,
table_linearize, table_linearize,
) )
from edkb_system.skills.common import blocks_to_plain_markdown from edkb_system.skills.common import blocks_to_plain_markdown, is_figure_rich_handbook
from edkb_system.skills.word_bridge import _kill_winword_pids, _list_winword_pids from edkb_system.skills.word_bridge import _kill_winword_pids, _list_winword_pids
@@ -281,6 +289,21 @@ def _cleanup_input_temp_files(input_path: Path) -> list[Path]:
def _should_run_ocr(profile, cfg, blocks: list, context: Context | None = None) -> bool: def _should_run_ocr(profile, cfg, blocks: list, context: Context | None = None) -> bool:
"""
判断当前文档是否需要跑 OCR。
核心逻辑:PPT 跳过;Word 仅在 pipeline 显式请求时跑;PDF 在扫描/整页图模式
或图文手册(有 image block)时强制跑,以便写入「图中文字」供问答。
Args:
profile: intake 文档画像。
cfg: SystemConfig。
blocks: loader 产出的块。
context: 可选上下文(含 scan_likely / figure_rich_handbook 等 extras)。
Returns:
True 表示应执行 edkb-ocr。
"""
if not blocks or not cfg.ocr.enable: if not blocks or not cfg.ocr.enable:
return False return False
if profile.file_type in {"ppt", "pptx"}: if profile.file_type in {"ppt", "pptx"}:
@@ -288,6 +311,11 @@ def _should_run_ocr(profile, cfg, blocks: list, context: Context | None = None)
pipeline_requests_ocr = "edkb-ocr" in profile.recommended_pipeline pipeline_requests_ocr = "edkb-ocr" in profile.recommended_pipeline
has_image_blocks = any(b.type == "image" for b in blocks) has_image_blocks = any(b.type == "image" for b in blocks)
extras = getattr(context, "extras", {}) or {} if context is not None else {}
# [STEP] 机械设计手册等:只要有图就 OCR,避免只剩正文导致问答丢图信息
if has_image_blocks and extras.get("figure_rich_handbook"):
return True
# Word documents often contain decorative or embedded images. If intake # Word documents often contain decorative or embedded images. If intake
# did not explicitly request OCR, do not force a slow OCR pass just because # did not explicitly request OCR, do not force a slow OCR pass just because
@@ -296,7 +324,6 @@ def _should_run_ocr(profile, cfg, blocks: list, context: Context | None = None)
return False return False
if profile.file_type == "pdf" and not pipeline_requests_ocr: if profile.file_type == "pdf" and not pipeline_requests_ocr:
extras = getattr(context, "extras", {}) or {}
return bool(extras.get("scan_likely") or extras.get("pdf_page_image_mode_pages")) return bool(extras.get("scan_likely") or extras.get("pdf_page_image_mode_pages"))
return pipeline_requests_ocr or has_image_blocks return pipeline_requests_ocr or has_image_blocks
@@ -592,6 +619,13 @@ def _run_one(
if blocks: if blocks:
ctx.images = sum(1 for b in blocks if b.type == "image") ctx.images = sum(1 for b in blocks if b.type == "image")
figure_rich_handbook = bool(
ctx.extras.get("figure_rich_handbook")
or is_figure_rich_handbook(file_path.name)
)
if figure_rich_handbook:
ctx.extras["figure_rich_handbook"] = True
should_ocr = _should_run_ocr(profile, cfg, blocks, ctx) should_ocr = _should_run_ocr(profile, cfg, blocks, ctx)
if should_ocr: if should_ocr:
_announce("ocr") _announce("ocr")
@@ -614,8 +648,13 @@ def _run_one(
for b in blocks for b in blocks
if b.type in {"heading", "paragraph"} if b.type in {"heading", "paragraph"}
) )
# [STEP] policy_text/flow 默认丢图;手册类必须保留 image+ocr_text 供问答
suppress_images = False suppress_images = False
if profile.file_type not in {"ppt", "pptx"} and not has_figure_anchor: if (
profile.file_type not in {"ppt", "pptx"}
and not has_figure_anchor
and not figure_rich_handbook
):
if policy_text and not has_non_flow_info and not has_page_image_mode: if policy_text and not has_non_flow_info and not has_page_image_mode:
suppress_images = True suppress_images = True
elif ( elif (
@@ -627,6 +666,8 @@ def _run_one(
if suppress_images: if suppress_images:
blocks = [b for b in blocks if b.type not in {"image", "ocr_text"}] blocks = [b for b in blocks if b.type not in {"image", "ocr_text"}]
trace_steps.append("edkb-image-suppress(no_figure_anchor)") trace_steps.append("edkb-image-suppress(no_figure_anchor)")
elif figure_rich_handbook:
trace_steps.append("edkb-image-keep(figure_rich_handbook)")
flow_info = {} flow_info = {}
if "edkb-flow-reconstruct" in profile.recommended_pipeline: if "edkb-flow-reconstruct" in profile.recommended_pipeline:
@@ -642,7 +683,9 @@ def _run_one(
encoding="utf-8", encoding="utf-8",
) )
text = blocks_to_plain_markdown(blocks) text = blocks_to_plain_markdown(
blocks, keep_figure_ocr=figure_rich_handbook
)
text = _inject_doc_header_from_flow(text, flow_mds) text = _inject_doc_header_from_flow(text, flow_mds)
elif tables is not None: elif tables is not None:
_announce("table linearize") _announce("table linearize")
+28 -1
View File
@@ -1,3 +1,11 @@
"""
edkb_system/skills/clean.py
用途:对 loader/OCR 产出的 markdown 做去重、排版与图注附着等清洗。
依赖:edkb_system.contracts.Context。
逻辑:由 controller 在 blocks→markdown 之后调用;需保留手册页图「图中文字」。
"""
from __future__ import annotations from __future__ import annotations
import base64 import base64
@@ -907,13 +915,28 @@ def _compact_remarks_to_single_line(text: str) -> str:
def _attach_ocr_lines_to_images(text: str) -> str: def _attach_ocr_lines_to_images(text: str) -> str:
"""
将散落的「图中文字」行重新挂到对应图片 markdown 行之后。
核心逻辑:抽出全部 OCR 行后,按出现顺序挂到 image/page-image 标记后;
支持带 URL 的 `![](data:…)` 以及手册整页图占位 `![page-image-N]`(无 URL)。
Args:
text: 清洗中的 markdown。
Returns:
OCR 行已附着到图片后的 markdown;无图时原样返回。
"""
lines = text.splitlines() lines = text.splitlines()
ocr_lines = [ln.strip() for ln in lines if ln.strip().startswith("图中文字:")] ocr_lines = [ln.strip() for ln in lines if ln.strip().startswith("图中文字:")]
if not ocr_lines: if not ocr_lines:
return text return text
kept = [ln for ln in lines if not ln.strip().startswith("图中文字:")] kept = [ln for ln in lines if not ln.strip().startswith("图中文字:")]
img_pat = re.compile(r"^!\[(?:image|page-image)-\d+\]\((?:data:image/|https?://)") # 含 data/http URL 的图,以及无 URL 的 page-image 占位(手册整页 OCR)
img_pat = re.compile(
r"^!\[(?:image|page-image)-\d+\](?:\((?:data:image/|https?://)[^)]*\))?$"
)
img_count = sum(1 for ln in kept if img_pat.match(ln.strip())) img_count = sum(1 for ln in kept if img_pat.match(ln.strip()))
if img_count <= 0: if img_count <= 0:
return text return text
@@ -927,6 +950,10 @@ def _attach_ocr_lines_to_images(text: str) -> str:
if img_pat.match(ln.strip()): if img_pat.match(ln.strip()):
out.append(ocr_lines[o_idx]) out.append(ocr_lines[o_idx])
o_idx += 1 o_idx += 1
# 多余 OCR 行仍保留,避免手册图注被静默丢弃
while o_idx < len(ocr_lines):
out.append(ocr_lines[o_idx])
o_idx += 1
return "\n".join(out) return "\n".join(out)
+82 -9
View File
@@ -1,3 +1,11 @@
"""
edkb_system/skills/common.py
用途:edkb 清洗链路的通用工具(哈希、OCR 载荷整理、blocks→markdown)。
依赖:edkb_system.contracts.Block。
逻辑:controller / export / loader 等技能复用;手册类图文保留策略也集中在此判定。
"""
from __future__ import annotations from __future__ import annotations
import hashlib import hashlib
@@ -9,6 +17,45 @@ from typing import Any
from edkb_system.contracts import Block from edkb_system.contracts import Block
# 机械设计手册等图文密集文档:清洗时需保留图片并写入 OCR「图中文字」供问答检索。
_FIGURE_RICH_HANDBOOK_KEYWORDS = (
"手册",
"圖冊",
"图册",
"图集",
"圖集",
"机械设计",
"機械設計",
"handbook",
"design manual",
)
def is_figure_rich_handbook(name: str) -> bool:
"""
判断文件名是否像「图文密集手册/设计手册」。
核心逻辑:文件名命中手册/图册/机械设计等关键词时返回 True,供 loader/controller
放宽嵌图保留、跳过 policy_text 丢图、并强制 OCR。
Args:
name: 文件名或 stem(可含扩展名)。
Returns:
True 表示应按图文手册策略处理。
"""
text = str(name or "").strip()
if not text:
return False
lowered = text.lower()
for keyword in _FIGURE_RICH_HANDBOOK_KEYWORDS:
if keyword.isascii():
if keyword in lowered:
return True
elif keyword in text:
return True
return False
def hash_text(text: str) -> str: def hash_text(text: str) -> str:
return hashlib.sha256(text.encode("utf-8")).hexdigest() return hashlib.sha256(text.encode("utf-8")).hexdigest()
@@ -162,7 +209,23 @@ def _page_image_structured_lines(payload: str) -> list[str]:
return lines return lines
def blocks_to_plain_markdown(blocks: list[Block]) -> str: def blocks_to_plain_markdown(
blocks: list[Block], *, keep_figure_ocr: bool = False
) -> str:
"""
将 block 列表转为纯文本 markdown(含可选图片与「图中文字」OCR)。
核心逻辑:按页排序输出 heading/paragraph/image;PDF 整页图在正文较多时默认抑制,
但 keep_figure_ocr=True(手册类)时始终保留 OCR 文案供问答检索。
Args:
blocks: 清洗后的内容块。
keep_figure_ocr: 为 True 时不因页内正文较多而丢弃 PDF 页图 OCR。
Returns:
markdown 字符串(末尾带换行)。
"""
def _is_meaningful_ocr_segment(text: str) -> bool: def _is_meaningful_ocr_segment(text: str) -> bool:
token = re.sub(r"\s+", "", text or "") token = re.sub(r"\s+", "", text or "")
if not token or re.fullmatch(r"[\W_]+", token): if not token or re.fullmatch(r"[\W_]+", token):
@@ -237,10 +300,15 @@ def blocks_to_plain_markdown(blocks: list[Block]) -> str:
) )
if is_pdf_page_image: if is_pdf_page_image:
ocr_text = ocr_by_image.get(b.id) ocr_text = ocr_by_image.get(b.id)
# [STEP] 手册类保留页图 OCR;普通 PDF 仍避免与正文重复的整页图噪声
suppress_pdf_page_image = ( suppress_pdf_page_image = (
page_body_chars.get(b.page, 0) >= 80 not keep_figure_ocr
or page_text_chars.get(b.page, 0) >= 120 and (
) and not _is_rich_ocr_payload(ocr_text or "") page_body_chars.get(b.page, 0) >= 80
or page_text_chars.get(b.page, 0) >= 120
)
and not _is_rich_ocr_payload(ocr_text or "")
)
if not suppress_pdf_page_image: if not suppress_pdf_page_image:
lines.append(f"![page-image-{b.page}]") lines.append(f"![page-image-{b.page}]")
if ocr_text and not suppress_pdf_page_image: if ocr_text and not suppress_pdf_page_image:
@@ -253,11 +321,13 @@ def blocks_to_plain_markdown(blocks: list[Block]) -> str:
lines.append(f"![image-{image_idx}]({data_uri})") lines.append(f"![image-{image_idx}]({data_uri})")
ocr_text = ocr_by_image.get(b.id) ocr_text = ocr_by_image.get(b.id)
if ocr_text: if ocr_text:
suppress_pptx_ocr = bool( suppress_pptx_ocr = (
b.meta and b.meta.get("page_image_source") == "pptx" not keep_figure_ocr
) and ( and bool(b.meta and b.meta.get("page_image_source") == "pptx")
page_body_chars.get(b.page, 0) >= 15 and (
or page_text_chars.get(b.page, 0) >= 40 page_body_chars.get(b.page, 0) >= 15
or page_text_chars.get(b.page, 0) >= 40
)
) )
if b.meta and b.meta.get("page_image"): if b.meta and b.meta.get("page_image"):
lines.extend(_page_image_structured_lines(ocr_text)) lines.extend(_page_image_structured_lines(ocr_text))
@@ -265,6 +335,9 @@ def blocks_to_plain_markdown(blocks: list[Block]) -> str:
lines.append(f"图中文字:{ocr_text}") lines.append(f"图中文字:{ocr_text}")
else: else:
lines.append("![image]") lines.append("![image]")
ocr_text = ocr_by_image.get(b.id)
if ocr_text and keep_figure_ocr:
lines.append(f"图中文字:{ocr_text}")
else: else:
lines.append(txt) lines.append(txt)
return "\n\n".join(lines).strip() + "\n" return "\n\n".join(lines).strip() + "\n"
+94 -3
View File
@@ -1,3 +1,11 @@
"""
edkb_system/skills/loader_pdf.py
用途:解析 PDF 为 Block 列表(正文、嵌入图、扫描页整页图)。
依赖:pypdf / pypdfium2、edkb_system.contracts、common.is_figure_rich_handbook。
逻辑:由 controller 在 PDF 分支调用;手册类文件名会放宽嵌图保留阈值。
"""
from __future__ import annotations from __future__ import annotations
import base64 import base64
@@ -7,6 +15,7 @@ import re
import xml.etree.ElementTree as ET import xml.etree.ElementTree as ET
from edkb_system.contracts import Block, Context from edkb_system.contracts import Block, Context
from edkb_system.skills.common import is_figure_rich_handbook
_PAGE_IMAGE_RENDER_SCALE = 0.75 _PAGE_IMAGE_RENDER_SCALE = 0.75
_PAGE_IMAGE_JPEG_QUALITY = 82 _PAGE_IMAGE_JPEG_QUALITY = 82
@@ -15,6 +24,9 @@ _DEFAULT_PAGE_TEXT_LIMIT = 120
_MIN_SCAN_IMAGE_BYTES = 4 * 1024 _MIN_SCAN_IMAGE_BYTES = 4 * 1024
_MIN_DEFAULT_IMAGE_BYTES = 16 * 1024 _MIN_DEFAULT_IMAGE_BYTES = 16 * 1024
_MIN_TEXT_HEAVY_IMAGE_BYTES = 24 * 1024 _MIN_TEXT_HEAVY_IMAGE_BYTES = 24 * 1024
# 图文手册:正文页也保留较大嵌入图,供后续 OCR「图中文字」。
_MIN_FIGURE_HANDBOOK_IMAGE_BYTES = 12 * 1024
_FIGURE_HANDBOOK_PAGE_TEXT_LIMIT = 400
_XFA_ROW_CONTAINER_TAGS = {"DATA"} _XFA_ROW_CONTAINER_TAGS = {"DATA"}
_XFA_SKIP_TAGS = { _XFA_SKIP_TAGS = {
"config", "config",
@@ -44,11 +56,33 @@ def _should_keep_embedded_image(
page_text_chars: int, page_text_chars: int,
scan_likely: bool, scan_likely: bool,
text_heavy_pdf: bool, text_heavy_pdf: bool,
figure_rich_handbook: bool = False,
) -> bool: ) -> bool:
"""
判断 PDF 页内嵌入图是否保留为 image block。
核心逻辑:扫描件放宽体积阈值;正文密集 PDF 默认只保留「少字页上的大图」;
手册类则允许正文页保留 ≥12KB 的图,避免机械设计图被滤掉。
Args:
data_size: 图片字节数。
page_text_chars: 当页提取到的正文字符数。
scan_likely: 是否判定为扫描件。
text_heavy_pdf: 是否全文偏文本密集。
figure_rich_handbook: 是否图文手册策略。
Returns:
True 表示保留该嵌入图。
"""
if data_size <= 0: if data_size <= 0:
return False return False
if scan_likely: if scan_likely:
return data_size >= _MIN_SCAN_IMAGE_BYTES return data_size >= _MIN_SCAN_IMAGE_BYTES
if figure_rich_handbook:
return (
data_size >= _MIN_FIGURE_HANDBOOK_IMAGE_BYTES
and page_text_chars <= _FIGURE_HANDBOOK_PAGE_TEXT_LIMIT
)
if text_heavy_pdf: if text_heavy_pdf:
return page_text_chars <= _TEXT_HEAVY_PAGE_TEXT_LIMIT and data_size >= _MIN_TEXT_HEAVY_IMAGE_BYTES return page_text_chars <= _TEXT_HEAVY_PAGE_TEXT_LIMIT and data_size >= _MIN_TEXT_HEAVY_IMAGE_BYTES
return page_text_chars <= 80 or data_size >= _MIN_DEFAULT_IMAGE_BYTES return page_text_chars <= 80 or data_size >= _MIN_DEFAULT_IMAGE_BYTES
@@ -181,7 +215,27 @@ def _should_use_page_image_mode(
image_count: int, image_count: int,
largest_ratio: float, largest_ratio: float,
total_ratio: float, total_ratio: float,
figure_rich_handbook: bool = False,
) -> bool: ) -> bool:
"""
判断当页是否改用「整页渲染图」模式(便于 OCR)。
核心逻辑:扫描件/少字大图页走整页图;手册类在嵌图很少但版面以图为主时也启用。
Args:
scan_likely / text_heavy_pdf: PDF 全局特征。
text_chars / image_count / largest_ratio / total_ratio: 当页特征。
figure_rich_handbook: 手册策略开关。
Returns:
True 表示渲染整页图而非仅保留嵌入图。
"""
if figure_rich_handbook:
# 手册扫描分片:嵌图提取失败时,用整页图兜底 OCR
if image_count == 0 and (largest_ratio >= 0.35 or total_ratio >= 0.4 or text_chars < 80):
return True
if largest_ratio >= 0.55 or total_ratio >= 0.65:
return True
if text_heavy_pdf and text_chars > _TEXT_HEAVY_PAGE_TEXT_LIMIT: if text_heavy_pdf and text_chars > _TEXT_HEAVY_PAGE_TEXT_LIMIT:
return False return False
if scan_likely: if scan_likely:
@@ -201,9 +255,22 @@ def _should_use_page_image_mode(
def _analysis_candidate_pages( def _analysis_candidate_pages(
page_payloads: list[dict], scan_likely: bool, text_heavy_pdf: bool page_payloads: list[dict],
scan_likely: bool,
text_heavy_pdf: bool,
figure_rich_handbook: bool = False,
) -> list[int]: ) -> list[int]:
if scan_likely: """
选出需要做版面/图片框分析的页码列表。
Args:
page_payloads: 每页 text/images 摘要。
scan_likely / text_heavy_pdf / figure_rich_handbook: 文档策略。
Returns:
1-based 页码列表。
"""
if scan_likely or figure_rich_handbook:
return [int(payload["page"]) for payload in page_payloads] return [int(payload["page"]) for payload in page_payloads]
if text_heavy_pdf: if text_heavy_pdf:
return [ return [
@@ -305,8 +372,21 @@ def _render_page_png(
def run(input_data: dict, context: Context) -> list[Block]: def run(input_data: dict, context: Context) -> list[Block]:
"""
加载 PDF 为 paragraph / image blocks。
核心逻辑:提取文本与嵌入图;扫描或手册类可渲染整页图;结果写入 context.extras。
Args:
input_data: 须含 file_path。
context: 流水线上下文(会写入 pages/images/extras)。
Returns:
Block 列表。
"""
file_path = Path(input_data["file_path"]) file_path = Path(input_data["file_path"])
blocks: list[Block] = [] blocks: list[Block] = []
figure_rich_handbook = is_figure_rich_handbook(file_path.name)
try: try:
from pypdf import PdfReader from pypdf import PdfReader
@@ -338,6 +418,7 @@ def run(input_data: dict, context: Context) -> list[Block]:
page_text_chars=len(text), page_text_chars=len(text),
scan_likely=False, scan_likely=False,
text_heavy_pdf=False, text_heavy_pdf=False,
figure_rich_handbook=figure_rich_handbook,
): ):
continue continue
ext = (getattr(img, "image_format", "") or "").lower() ext = (getattr(img, "image_format", "") or "").lower()
@@ -366,10 +447,14 @@ def run(input_data: dict, context: Context) -> list[Block]:
page_text_chars=len(str(payload.get("text") or "")), page_text_chars=len(str(payload.get("text") or "")),
scan_likely=scan_likely, scan_likely=scan_likely,
text_heavy_pdf=text_heavy_pdf, text_heavy_pdf=text_heavy_pdf,
figure_rich_handbook=figure_rich_handbook,
) )
] ]
candidate_pages = _analysis_candidate_pages( candidate_pages = _analysis_candidate_pages(
page_payloads, scan_likely, text_heavy_pdf page_payloads,
scan_likely,
text_heavy_pdf,
figure_rich_handbook=figure_rich_handbook,
) )
image_boxes_by_page: dict[int, list[tuple[float, float, float, float]]] = {} image_boxes_by_page: dict[int, list[tuple[float, float, float, float]]] = {}
pdfium_doc = None pdfium_doc = None
@@ -402,6 +487,7 @@ def run(input_data: dict, context: Context) -> list[Block]:
image_count=len(page_images) or int(stats["count"]), image_count=len(page_images) or int(stats["count"]),
largest_ratio=float(stats["largest_ratio"]), largest_ratio=float(stats["largest_ratio"]),
total_ratio=float(stats["total_ratio"]), total_ratio=float(stats["total_ratio"]),
figure_rich_handbook=figure_rich_handbook,
) )
if text: if text:
@@ -476,6 +562,11 @@ def run(input_data: dict, context: Context) -> list[Block]:
context.extras["scan_likely"] = True context.extras["scan_likely"] = True
if text_heavy_pdf: if text_heavy_pdf:
context.extras["text_heavy_pdf"] = True context.extras["text_heavy_pdf"] = True
if figure_rich_handbook:
context.extras["figure_rich_handbook"] = True
context.warnings.append(
"figure-rich handbook mode: keep embedded figures and prefer OCR captions"
)
if page_image_mode_pages: if page_image_mode_pages:
context.extras["pdf_page_image_mode_pages"] = page_image_mode_pages context.extras["pdf_page_image_mode_pages"] = page_image_mode_pages
context.warnings.append( context.warnings.append(
@@ -17,12 +17,38 @@ def test_build_usage_report(app):
db.session.add(ChatLog(user_id=user.id, agent_id=agent.id, query='hi', answer='ok', tokens_used=1)) db.session.add(ChatLog(user_id=user.id, agent_id=agent.id, query='hi', answer='ok', tokens_used=1))
db.session.commit() db.session.commit()
data = report_service.build_usage_report(user_page=1, user_page_size=10) data = report_service.build_usage_report(user_page=1, user_page_size=10, range_key='30d')
assert data['total'] == 1 assert data['total'] == 1
assert data['range'] == '30d'
assert data['by_user'][0]['username'] == 'report-user' assert data['by_user'][0]['username'] == 'report-user'
assert data['by_agent'][0]['agent'] == 'report-agent' assert data['by_agent'][0]['agent'] == 'report-agent'
def test_build_usage_report_excludes_outside_range(app):
"""超出所选时间范围的聊天日志不计入统计。"""
from datetime import datetime, timedelta
with app.app_context():
agent = Agent(name='range-agent', type='api', dify_app_id='app-range', dify_api_key='key-range')
user = User(username='range-user', email='range@example.com', role='user')
db.session.add_all([agent, user])
db.session.flush()
old = ChatLog(user_id=user.id, agent_id=agent.id, query='old', answer='ok', tokens_used=1)
recent = ChatLog(user_id=user.id, agent_id=agent.id, query='new', answer='ok', tokens_used=1)
db.session.add_all([old, recent])
db.session.commit()
old.created_at = datetime.utcnow() - timedelta(days=40)
db.session.commit()
data = report_service.build_usage_report(user_page=1, user_page_size=10, range_key='7d')
assert data['range'] == '7d'
assert data['total'] == 1
assert data['by_user'][0]['count'] == 1
invalid = report_service.resolve_usage_range_start('bad')
assert invalid[0] == '30d'
def test_build_feedback_report(app): def test_build_feedback_report(app):
with app.app_context(): with app.app_context():
db.session.add(Feedback(score=5)) db.session.add(Feedback(score=5))
@@ -21,3 +21,34 @@ def test_approve_and_reject_user(app):
user_service.reject_user(user.id) user_service.reject_user(user.id)
db.session.refresh(user) db.session.refresh(user)
assert user.status == 'rejected' assert user.status == 'rejected'
def test_list_users_sort_by_username_and_department(app):
"""分页列表支持按用户名 / 部门排序,非法 sort_by 回退按 id。"""
with app.app_context():
db.session.add_all(
[
User(username='z-user', email='z@example.com', department='品保部', role='user', status='active'),
User(username='a-user', email='a@example.com', department='资讯', role='user', status='active'),
User(username='m-user', email='m@example.com', department='资讯', role='user', status='active'),
]
)
db.session.commit()
by_name = user_service.list_users(
{'page': '1', 'page_size': '20', 'sort_by': 'username', 'sort_dir': 'asc'}
)
assert [u['username'] for u in by_name['items'] if u['username'].endswith('-user')] == [
'a-user',
'm-user',
'z-user',
]
by_dept_desc = user_service.list_users(
{'page': '1', 'page_size': '20', 'sort_by': 'department', 'sort_dir': 'desc'}
)
depts = [u['department'] for u in by_dept_desc['items'] if u['username'].endswith('-user')]
assert depts == sorted(depts, reverse=True)
fallback = user_service.resolve_users_order_by({'sort_by': 'role', 'sort_dir': 'asc'})
assert len(fallback) == 1
+12 -3
View File
@@ -7,7 +7,7 @@ import { requestJson } from '@/shared/api/client';
import type { AdminUserRow } from '../types/admin.types'; import type { AdminUserRow } from '../types/admin.types';
import type { AdminDashboardBadges, AdminDashboardSummary } from '../types/dashboard.types'; import type { AdminDashboardBadges, AdminDashboardSummary } from '../types/dashboard.types';
import type { PaginatedResult } from '@/shared/types/pagination.types'; import type { PaginatedResult } from '@/shared/types/pagination.types';
import type { UsageReport } from '../types/report.types'; import type { UsageReport, UsageRangeKey } from '../types/report.types';
const auth = () => ({ headers: getAuthHeaders() }); const auth = () => ({ headers: getAuthHeaders() });
const jsonAuth = () => ({ headers: { 'Content-Type': 'application/json', ...getAuthHeaders() } }); const jsonAuth = () => ({ headers: { 'Content-Type': 'application/json', ...getAuthHeaders() } });
@@ -27,11 +27,15 @@ export interface ListAdminUsersPageParams {
employee_id?: string; employee_id?: string;
phone_number?: string; phone_number?: string;
hideRejected?: boolean; hideRejected?: boolean;
/** 排序列:username | department */
sortBy?: 'username' | 'department';
/** 排序方向 */
sortDir?: 'asc' | 'desc';
} }
/** /**
* 分页拉取用户列表(服务端筛选 + 分页,供用户管理页使用)。 * 分页拉取用户列表(服务端筛选 + 分页 + 排序,供用户管理页使用)。
* @param params - 页码、每页条数与各字段模糊筛选 * @param params - 页码、每页条数、字段模糊筛选与 sortBy/sortDir
*/ */
export const listAdminUsersPage = (params: ListAdminUsersPageParams) => { export const listAdminUsersPage = (params: ListAdminUsersPageParams) => {
const qs = new URLSearchParams(); const qs = new URLSearchParams();
@@ -53,6 +57,8 @@ export const listAdminUsersPage = (params: ListAdminUsersPageParams) => {
if (value) qs.set(queryKey, value); if (value) qs.set(queryKey, value);
} }
if (params.hideRejected) qs.set('hide_rejected', 'true'); if (params.hideRejected) qs.set('hide_rejected', 'true');
if (params.sortBy) qs.set('sort_by', params.sortBy);
if (params.sortDir) qs.set('sort_dir', params.sortDir);
return requestJson<PaginatedResult<AdminUserRow>>(`/api/admin/users?${qs.toString()}`, auth()); return requestJson<PaginatedResult<AdminUserRow>>(`/api/admin/users?${qs.toString()}`, auth());
}; };
export const createAdminUser = (payload: Record<string, unknown>) => export const createAdminUser = (payload: Record<string, unknown>) =>
@@ -254,12 +260,15 @@ export const getAdminDashboardBadges = () =>
export interface AdminUsageReportParams { export interface AdminUsageReportParams {
user_page?: number; user_page?: number;
user_page_size?: number; user_page_size?: number;
/** 时间范围:7d | 30d | 90d | 180d | 365d */
range?: UsageRangeKey;
} }
export const getAdminUsageReport = (params: AdminUsageReportParams = {}) => { export const getAdminUsageReport = (params: AdminUsageReportParams = {}) => {
const qs = new URLSearchParams(); const qs = new URLSearchParams();
if (params.user_page != null) qs.set('user_page', String(params.user_page)); if (params.user_page != null) qs.set('user_page', String(params.user_page));
if (params.user_page_size != null) qs.set('user_page_size', String(params.user_page_size)); if (params.user_page_size != null) qs.set('user_page_size', String(params.user_page_size));
if (params.range) qs.set('range', params.range);
const query = qs.toString(); const query = qs.toString();
return requestJson<UsageReport>( return requestJson<UsageReport>(
`/api/admin/reports/usage${query ? `?${query}` : ''}`, `/api/admin/reports/usage${query ? `?${query}` : ''}`,
@@ -1,25 +1,36 @@
/** /**
* features/admin/modules/departments/DepartmentsPage.vue * features/admin/modules/departments/DepartmentsPage.vue
* 部门管理独立页面。路由:/admin/departments * 用途:部门管理独立页面——全宽表格列表 + 列排序 + 创建/编辑居中弹窗。
* 依赖:useDepartmentsAdmin、SortableTableHeader、DepartmentFormModal、DeleteConfirmDialog。
* 逻辑:路由 /admin/departments;表头排序复用 shared SortableTableHeader + useTableSort。
*/ */
<script setup lang="ts"> <script setup lang="ts">
import { onMounted } from 'vue'; import { onMounted } from 'vue';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import { Edit, Trash2 } from 'lucide-vue-next'; import { Edit, Plus, Search, Trash2 } from 'lucide-vue-next';
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue'; import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
import SortableTableHeader from '@/shared/components/SortableTableHeader.vue';
import DepartmentFormModal from './components/DepartmentFormModal.vue';
import { useDepartmentsAdmin } from './composables/useDepartmentsAdmin'; import { useDepartmentsAdmin } from './composables/useDepartmentsAdmin';
const { t } = useI18n(); const { t } = useI18n();
const { const {
departments, filteredDepartments,
editingDept, form,
searchQuery,
sortKey,
sortDir,
isLoading, isLoading,
isSaving,
showFormModal,
showDeleteConfirmDialog, showDeleteConfirmDialog,
deleteConfirmMessage, deleteConfirmMessage,
loadAll, loadAll,
resetForm, toggleSort,
editDepartment, openCreateModal,
openEditModal,
closeFormModal,
saveDepartment, saveDepartment,
deleteDepartment, deleteDepartment,
closeDeleteConfirm, closeDeleteConfirm,
@@ -32,127 +43,137 @@ onMounted(() => {
</script> </script>
<template> <template>
<section class="section-gap animate-fade-in-up"> <section class="admin-table-section animate-fade-in-up">
<div v-if="isLoading" class="flex items-center justify-center py-20"> <div v-if="isLoading" class="flex items-center justify-center py-20">
<div class="animate-spin rounded-full h-10 w-10 border-b-2 border-brand-600" /> <div class="animate-spin rounded-full h-10 w-10 border-b-2 border-brand-600" />
</div> </div>
<template v-else> <template v-else>
<div class="flex items-center justify-between"> <div class="admin-table-header admin-table-header--stacked">
<div> <div>
<h2 class="section-title">{{ t('admin.dept.title') }}</h2> <h2 class="section-title">{{ t('admin.dept.title') }}</h2>
<p class="section-desc mt-1">{{ t('admin.dept.subtitle') }}</p> <p class="section-desc mt-1">{{ t('admin.dept.subtitle') }}</p>
</div> </div>
<button
type="button"
class="flex items-center gap-2 px-4 py-2 bg-brand-600 text-white rounded-xl hover:bg-brand-700 transition-all shadow-lg shadow-brand-200 active:scale-95 text-sm font-medium"
@click="openCreateModal"
>
<Plus class="w-4 h-4" />
<span>{{ t('admin.dept.add') }}</span>
</button>
</div> </div>
<div class="grid grid-cols-1 lg:grid-cols-3 gap-6"> <div class="admin-table-filters--inline gap-3">
<div class="lg:col-span-1 card p-6 shadow-sm h-fit"> <div class="relative flex-1 min-w-[200px] max-w-sm">
<h3 class="font-bold text-primary mb-4"> <Search class="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted pointer-events-none" />
{{ editingDept.id ? t('admin.dept.edit') : t('admin.dept.add') }} <input
</h3> v-model="searchQuery"
<div class="form-stack"> type="search"
<div class="space-y-1.5"> class="admin-table-filter-input w-full pl-9"
<label class="label-field block">{{ t('admin.dept.fields.name') }}</label> :placeholder="t('admin.dept.searchPlaceholder')"
<input />
v-model="editingDept.name"
class="input-field text-sm"
:placeholder="t('admin.dept.fields.namePlaceholder')"
/>
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.dept.fields.code') }}</label>
<input
v-model="editingDept.code"
class="input-field text-sm"
:placeholder="t('admin.dept.fields.codePlaceholder')"
/>
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.dept.fields.company') }}</label>
<input
v-model="editingDept.company"
class="input-field text-sm"
:placeholder="t('admin.dept.fields.companyPlaceholder')"
/>
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.dept.fields.description') }}</label>
<textarea
v-model="editingDept.description"
rows="3"
class="input-field text-sm"
:placeholder="t('admin.dept.fields.descriptionPlaceholder')"
/>
</div>
<div class="flex justify-end gap-2 pt-2">
<button
v-if="editingDept.id"
type="button"
class="btn-ghost btn-sm"
@click="resetForm"
>
{{ t('admin.cancel') }}
</button>
<button type="button" class="btn-primary btn-sm" @click="saveDepartment">
{{ editingDept.id ? t('admin.update') : t('admin.add') }}
</button>
</div>
</div>
</div> </div>
</div>
<div class="lg:col-span-2 admin-table-section"> <div class="admin-table-wrap">
<div v-if="departments.length === 0" class="p-8 text-center text-muted"> <!-- 列宽:名称 / 编码 / 公司 / 操作 -->
{{ t('admin.dept.noDepts') }} <table class="admin-table table-fixed">
</div> <colgroup>
<table v-else class="admin-table"> <col class="w-[25%]" />
<thead> <col class="w-[20%]" />
<tr> <col class="w-[35%]" />
<th class="px-6 py-3 text-xs font-semibold text-muted uppercase"> <col class="w-[15%]" />
{{ t('admin.dept.headers.name') }} </colgroup>
</th> <thead>
<th class="px-6 py-3 text-xs font-semibold text-muted uppercase"> <tr>
{{ t('admin.dept.headers.code') }} <th class="px-6 py-4 text-left text-xs">
</th> <SortableTableHeader
<th class="px-6 py-3 text-xs font-semibold text-muted uppercase"> column-key="name"
{{ t('admin.dept.headers.company') }} :label="t('admin.dept.headers.name')"
</th> :active-key="sortKey"
<th class="px-6 py-3 text-xs font-semibold text-muted uppercase text-right"> :direction="sortDir"
{{ t('admin.dept.headers.actions') }} @sort="toggleSort"
</th> />
</tr> </th>
</thead> <th class="px-6 py-4 text-left text-xs">
<tbody class="divide-y divide-subtle"> <SortableTableHeader
<tr v-for="d in departments" :key="d.id"> column-key="code"
<td class="px-6 py-4"> :label="t('admin.dept.headers.code')"
<div class="font-medium text-primary text-sm">{{ d.name }}</div> :active-key="sortKey"
<div class="text-xs text-muted truncate max-w-xs mt-0.5">{{ d.description }}</div> :direction="sortDir"
</td> @sort="toggleSort"
<td class="px-6 py-4 text-sm text-muted font-mono">{{ d.code || '-' }}</td> />
<td class="px-6 py-4 text-sm text-muted">{{ d.company || '-' }}</td> </th>
<td class="px-6 py-4 text-right flex justify-end gap-2"> <th class="px-6 py-4 text-left text-xs">
<SortableTableHeader
column-key="company"
:label="t('admin.dept.headers.company')"
:active-key="sortKey"
:direction="sortDir"
@sort="toggleSort"
/>
</th>
<th class="px-6 py-4 text-right text-xs">{{ t('admin.dept.headers.actions') }}</th>
</tr>
</thead>
<tbody>
<tr v-if="filteredDepartments.length === 0">
<td colspan="4" class="px-6 admin-table-empty">
{{ searchQuery.trim() ? t('admin.dept.noSearchResults') : t('admin.dept.noDepts') }}
</td>
</tr>
<tr v-for="d in filteredDepartments" :key="d.id" class="group">
<td class="px-6 py-4">
<div class="font-medium text-primary text-sm truncate" :title="d.name">{{ d.name }}</div>
<div
v-if="d.description"
class="text-xs text-muted truncate mt-0.5"
:title="d.description"
>
{{ d.description }}
</div>
</td>
<td class="px-6 py-4 text-sm text-muted font-mono whitespace-nowrap truncate" :title="d.code || '-'">
{{ d.code || '-' }}
</td>
<td class="px-6 py-4 text-sm text-muted truncate" :title="d.company || '-'">
{{ d.company || '-' }}
</td>
<td class="px-6 py-4">
<div class="flex justify-end gap-1">
<button <button
type="button" type="button"
class="p-1.5 text-blue-600 hover:bg-blue-50 rounded-lg transition-colors" class="p-1.5 text-indigo-600 hover:bg-indigo-50 rounded-lg transition-colors"
@click="editDepartment(d)" :title="t('admin.dept.actions.edit')"
@click="openEditModal(d)"
> >
<Edit class="w-4 h-4" /> <Edit class="w-4 h-4" />
</button> </button>
<button <button
type="button" type="button"
class="p-1.5 text-red-600 hover:bg-red-50 rounded-lg transition-colors" class="p-1.5 text-red-600 hover:bg-red-50 rounded-lg transition-colors"
:title="t('admin.dept.actions.delete')"
@click="deleteDepartment(d.id)" @click="deleteDepartment(d.id)"
> >
<Trash2 class="w-4 h-4" /> <Trash2 class="w-4 h-4" />
</button> </button>
</td> </div>
</tr> </td>
</tbody> </tr>
</table> </tbody>
</div> </table>
</div> </div>
</template> </template>
<DepartmentFormModal
:visible="showFormModal"
:form="form"
:is-saving="isSaving"
@close="closeFormModal"
@save="saveDepartment"
/>
<DeleteConfirmDialog <DeleteConfirmDialog
v-model="showDeleteConfirmDialog" v-model="showDeleteConfirmDialog"
:message="deleteConfirmMessage" :message="deleteConfirmMessage"
@@ -0,0 +1,94 @@
/**
* features/admin/modules/departments/components/DepartmentFormModal.vue
* 用途:部门创建/编辑居中弹窗。
* 依赖:DepartmentFormState、admin 通用 modal 样式。
* 逻辑:DepartmentsPage 打开本组件;提交时 emit save,由 useDepartmentsAdmin 调 API。
*/
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import type { DepartmentFormState } from '@/features/admin/types/department.types';
defineProps<{
visible: boolean;
form: DepartmentFormState;
isSaving: boolean;
}>();
const emit = defineEmits<{
close: [];
save: [];
}>();
const { t } = useI18n();
</script>
<template>
<div v-if="visible" class="admin-modal-overlay animate-fade-in items-center">
<div class="admin-modal-panel max-w-lg max-h-[92vh] scale-100">
<div class="px-5 sm:px-8 pt-5 sm:pt-7 pb-4 border-b border-subtle">
<h3 class="section-title">
{{ form.id ? t('admin.dept.edit') : t('admin.dept.add') }}
</h3>
</div>
<div class="px-5 sm:px-8 py-5 space-y-4 overflow-y-auto">
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.dept.fields.name') }}</label>
<input
v-model="form.name"
type="text"
class="input-field text-sm"
:placeholder="t('admin.dept.fields.namePlaceholder')"
/>
</div>
<div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.dept.fields.code') }}</label>
<input
v-model="form.code"
type="text"
class="input-field text-sm"
:placeholder="t('admin.dept.fields.codePlaceholder')"
/>
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.dept.fields.company') }}</label>
<input
v-model="form.company"
type="text"
class="input-field text-sm"
:placeholder="t('admin.dept.fields.companyPlaceholder')"
/>
</div>
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.dept.fields.description') }}</label>
<textarea
v-model="form.description"
rows="3"
class="input-field text-sm resize-y"
:placeholder="t('admin.dept.fields.descriptionPlaceholder')"
/>
</div>
</div>
<div class="admin-modal-footer">
<button type="button" class="btn-ghost" @click="emit('close')">
{{ t('admin.cancel') }}
</button>
<button
type="button"
class="btn-primary disabled:opacity-70"
:disabled="isSaving"
@click="emit('save')"
>
{{
isSaving
? t('admin.save') + '...'
: form.id
? t('admin.update')
: t('admin.add')
}}
</button>
</div>
</div>
</div>
</template>
@@ -1,8 +1,10 @@
/** /**
* features/admin/modules/departments/composables/useDepartmentsAdmin.ts * features/admin/modules/departments/composables/useDepartmentsAdmin.ts
* 部门管理:列表、创建、编辑、删除。 * 用途:部门管理列表、搜索过滤、列排序、创建/编辑弹窗、删除。
* 依赖:admin.api、department.types、useMessage、useTableSort。
* 逻辑:DepartmentsPage 调用本 composable;排序状态委托 shared useTableSort。
*/ */
import { ref } from 'vue'; import { computed, ref } from 'vue';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import { import {
createAdminDepartment, createAdminDepartment,
@@ -11,24 +13,63 @@ import {
updateAdminDepartment, updateAdminDepartment,
} from '@/features/admin/api/admin.api'; } from '@/features/admin/api/admin.api';
import { useMessage } from '@/shared/composables/useMessage'; import { useMessage } from '@/shared/composables/useMessage';
import { useTableSort } from '@/shared/composables/useTableSort';
import type { AdminDepartmentRow } from '@/features/admin/types/admin.types'; import type { AdminDepartmentRow } from '@/features/admin/types/admin.types';
import { import {
createEmptyDepartmentForm, createEmptyDepartmentForm,
departmentRowToForm,
type DepartmentFormState, type DepartmentFormState,
} from '@/features/admin/types/department.types'; } from '@/features/admin/types/department.types';
/** 部门表可排序列 */
export type DeptSortKey = 'name' | 'code' | 'company';
export function useDepartmentsAdmin() { export function useDepartmentsAdmin() {
const { t } = useI18n(); const { t } = useI18n();
const msg = useMessage(); const msg = useMessage();
const departments = ref<AdminDepartmentRow[]>([]); const departments = ref<AdminDepartmentRow[]>([]);
const editingDept = ref<DepartmentFormState>(createEmptyDepartmentForm()); const form = ref<DepartmentFormState>(createEmptyDepartmentForm());
const searchQuery = ref('');
const { sortKey, sortDir, toggleSort, sortItems } = useTableSort<DeptSortKey>({
initialKey: 'name',
initialDir: 'asc',
});
const isLoading = ref(true); const isLoading = ref(true);
const isSaving = ref(false);
const showFormModal = ref(false);
const showDeleteConfirmDialog = ref(false); const showDeleteConfirmDialog = ref(false);
const deleteConfirmMessage = ref(''); const deleteConfirmMessage = ref('');
let deleteConfirmAction: (() => Promise<void> | void) | null = null; let deleteConfirmAction: (() => Promise<void> | void) | null = null;
/**
* 先按关键词过滤,再按当前排序列排序。
* 核心逻辑:模糊匹配四字段 → 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,
);
});
/**
* 拉取部门列表并写入 departments。
* @returns Promise<void>
*/
const loadDepartments = async (): Promise<void> => { const loadDepartments = async (): Promise<void> => {
try { try {
departments.value = await listAdminDepartments(); departments.value = await listAdminDepartments();
@@ -38,23 +79,37 @@ export function useDepartmentsAdmin() {
} }
}; };
/**
* 页面初始化:加载部门列表并结束 loading。
* @returns Promise<void>
*/
const loadAll = async (): Promise<void> => { const loadAll = async (): Promise<void> => {
isLoading.value = true; isLoading.value = true;
await loadDepartments(); await loadDepartments();
isLoading.value = false; isLoading.value = false;
}; };
/**
* 打开删除确认对话框并绑定确认后的删除动作。
* @param message - 确认文案
* @param action - 用户确认后执行的异步删除逻辑
*/
const openDeleteConfirm = (message: string, action: () => Promise<void> | void): void => { const openDeleteConfirm = (message: string, action: () => Promise<void> | void): void => {
deleteConfirmMessage.value = message; deleteConfirmMessage.value = message;
deleteConfirmAction = action; deleteConfirmAction = action;
showDeleteConfirmDialog.value = true; showDeleteConfirmDialog.value = true;
}; };
/** 关闭删除确认对话框并清空待执行动作。 */
const closeDeleteConfirm = (): void => { const closeDeleteConfirm = (): void => {
showDeleteConfirmDialog.value = false; showDeleteConfirmDialog.value = false;
deleteConfirmAction = null; deleteConfirmAction = null;
}; };
/**
* 执行删除确认对话框中绑定的删除动作。
* @returns Promise<void>
*/
const confirmDelete = async (): Promise<void> => { const confirmDelete = async (): Promise<void> => {
if (!deleteConfirmAction) return; if (!deleteConfirmAction) return;
try { try {
@@ -64,44 +119,63 @@ export function useDepartmentsAdmin() {
} }
}; };
const resetForm = (): void => { /** 打开「添加部门」弹窗并重置表单。 */
editingDept.value = createEmptyDepartmentForm(); const openCreateModal = (): void => {
form.value = createEmptyDepartmentForm();
showFormModal.value = true;
}; };
const editDepartment = (dept: AdminDepartmentRow): void => { /**
editingDept.value = { * 打开「编辑部门」弹窗并回填选中行数据。
id: dept.id, * @param dept - 待编辑的部门行
name: dept.name, */
code: dept.code || '', const openEditModal = (dept: AdminDepartmentRow): void => {
company: dept.company || '', form.value = departmentRowToForm(dept);
description: dept.description || '', showFormModal.value = true;
};
}; };
/** 关闭创建/编辑弹窗并重置表单。 */
const closeFormModal = (): void => {
showFormModal.value = false;
form.value = createEmptyDepartmentForm();
};
/**
* 保存部门:有 id 则更新,否则新建。
* 核心逻辑:校验名称 → 调 create/update API → 刷新列表并关闭弹窗。
* @returns Promise<void>
*/
const saveDepartment = async (): Promise<void> => { const saveDepartment = async (): Promise<void> => {
if (!editingDept.value.name?.trim()) { if (!form.value.name?.trim()) {
msg.warning(t('admin.dept.msg.nameRequired')); msg.warning(t('admin.dept.msg.nameRequired'));
return; return;
} }
isSaving.value = true;
try { try {
const payload = { const payload = {
name: editingDept.value.name, name: form.value.name.trim(),
code: editingDept.value.code, code: form.value.code?.trim() || '',
company: editingDept.value.company, company: form.value.company?.trim() || '',
description: editingDept.value.description, description: form.value.description?.trim() || '',
}; };
if (editingDept.value.id) { if (form.value.id) {
await updateAdminDepartment(editingDept.value.id, payload); await updateAdminDepartment(form.value.id, payload);
} else { } else {
await createAdminDepartment(payload); await createAdminDepartment(payload);
} }
closeFormModal();
await loadDepartments(); await loadDepartments();
resetForm();
} catch (e) { } catch (e) {
msg.error((e as Error).message || t('admin.msg.failed')); msg.error((e as Error).message || t('admin.msg.failed'));
} finally {
isSaving.value = false;
} }
}; };
/**
* 删除指定部门,删除前弹出确认框。
* @param id - 部门主键
*/
const deleteDepartment = (id: number): void => { const deleteDepartment = (id: number): void => {
openDeleteConfirm(t('admin.dept.confirmDelete'), async () => { openDeleteConfirm(t('admin.dept.confirmDelete'), async () => {
try { try {
@@ -116,13 +190,21 @@ export function useDepartmentsAdmin() {
return { return {
departments, departments,
editingDept, filteredDepartments,
form,
searchQuery,
sortKey,
sortDir,
isLoading, isLoading,
isSaving,
showFormModal,
showDeleteConfirmDialog, showDeleteConfirmDialog,
deleteConfirmMessage, deleteConfirmMessage,
loadAll, loadAll,
resetForm, toggleSort,
editDepartment, openCreateModal,
openEditModal,
closeFormModal,
saveDepartment, saveDepartment,
deleteDepartment, deleteDepartment,
closeDeleteConfirm, closeDeleteConfirm,
@@ -1,6 +1,8 @@
/** /**
* features/admin/modules/permissions/PermissionsPage.vue * features/admin/modules/permissions/PermissionsPage.vue
* 用户权限矩阵独立页面。路由:/admin/permissions * 用途:应用权限矩阵独立页面(用户 / 真实姓名 / 部门 + Agent 勾选)。
* 依赖:usePermissionsAdmin、BatchPermissionModal、PaginationBar。
* 逻辑:路由 /admin/permissions;左侧用户相关列 sticky,右侧为各应用权限列。
*/ */
<script setup lang="ts"> <script setup lang="ts">
import { onMounted } from 'vue'; import { onMounted } from 'vue';
@@ -115,12 +117,17 @@ onMounted(() => {
/> />
</th> </th>
<th <th
class="px-6 py-4 text-left text-sm sticky left-12 admin-table-sticky-head z-20 w-64 shadow-[2px_0_5px_-2px_rgba(0,0,0,0.1)]" class="px-6 py-4 text-left text-sm sticky left-12 admin-table-sticky-head z-20 w-56"
> >
{{ t('admin.perm.headers.user') }} {{ t('admin.perm.headers.user') }}
</th> </th>
<th <th
class="px-6 py-4 text-left text-sm sticky left-[19rem] admin-table-sticky-head z-20 w-40 border-r border-subtle shadow-[2px_0_5px_-2px_rgba(0,0,0,0.1)]" class="px-6 py-4 text-left text-sm sticky left-[17rem] admin-table-sticky-head z-20 w-36"
>
{{ t('admin.perm.headers.realName') }}
</th>
<th
class="px-6 py-4 text-left text-sm sticky left-[26rem] admin-table-sticky-head z-20 w-40 border-r border-subtle shadow-[2px_0_5px_-2px_rgba(0,0,0,0.1)]"
> >
{{ t('admin.perm.headers.dept') }} {{ t('admin.perm.headers.dept') }}
</th> </th>
@@ -148,25 +155,25 @@ onMounted(() => {
@change="toggleUserSelection(user.id)" @change="toggleUserSelection(user.id)"
/> />
</td> </td>
<td class="px-6 py-4 sticky left-12 admin-table-sticky-cell z-20 shadow-[2px_0_5px_-2px_rgba(0,0,0,0.05)]"> <td class="px-6 py-4 sticky left-12 admin-table-sticky-cell z-20">
<div class="flex items-center gap-3"> <div class="flex items-center gap-3">
<div <div
class="w-8 h-8 rounded-full bg-gradient-to-br from-brand-100 to-indigo-100 text-brand-600 flex items-center justify-center font-bold text-sm" class="w-8 h-8 rounded-full bg-gradient-to-br from-brand-100 to-indigo-100 text-brand-600 flex items-center justify-center font-bold text-sm"
> >
{{ user.username.charAt(0).toUpperCase() }} {{ user.username.charAt(0).toUpperCase() }}
</div> </div>
<div class="truncate max-w-[150px]"> <div class="font-medium text-primary text-sm truncate max-w-[120px]" :title="user.username">
<div class="font-medium text-primary truncate" :title="user.username"> {{ user.username }}
{{ user.username }}
</div>
<div class="text-xs text-muted truncate" :title="user.email">
{{ user.email }}
</div>
</div> </div>
</div> </div>
</td> </td>
<td class="px-6 py-4 sticky left-[17rem] admin-table-sticky-cell z-20">
<div class="text-sm text-primary truncate" :title="user.real_name || '-'">
{{ user.real_name || '-' }}
</div>
</td>
<td <td
class="px-6 py-4 sticky left-[19rem] admin-table-sticky-cell z-20 border-r border-subtle shadow-[2px_0_5px_-2px_rgba(0,0,0,0.05)]" class="px-6 py-4 sticky left-[26rem] admin-table-sticky-cell z-20 border-r border-subtle shadow-[2px_0_5px_-2px_rgba(0,0,0,0.05)]"
> >
<div class="text-sm text-muted truncate" :title="user.department"> <div class="text-sm text-muted truncate" :title="user.department">
{{ user.department || '-' }} {{ user.department || '-' }}
@@ -1,6 +1,8 @@
/** /**
* features/admin/modules/reports/ReportsPage.vue * features/admin/modules/reports/ReportsPage.vue
* 管理后台报表独立页面。路由:/admin/reports/:table? * 用途:管理后台报表独立页面(多表浏览、列筛选、聊天日志批量操作)。
* 依赖:useReportsAdmin、DeleteConfirmDialog。
* 逻辑:路由 /admin/reports/:table?;列宽由 composable 默认值与本地偏好控制。
*/ */
<script setup lang="ts"> <script setup lang="ts">
import { onMounted } from 'vue'; import { onMounted } from 'vue';
@@ -13,6 +15,8 @@ const { t } = useI18n();
const { const {
usageReport, usageReport,
usageRange,
usageRangeOptions,
usageUserPage, usageUserPage,
usageUserPageSize, usageUserPageSize,
usageUserPageSizeOptions, usageUserPageSizeOptions,
@@ -260,7 +264,7 @@ onMounted(() => {
<th <th
v-for="key in visibleReportKeys" v-for="key in visibleReportKeys"
:key="key" :key="key"
class="px-6 py-4 whitespace-nowrap align-top relative" class="px-3 py-4 whitespace-nowrap align-top relative"
:style="getColumnWidthStyle(key)" :style="getColumnWidthStyle(key)"
:draggable="true" :draggable="true"
@dragstart="onColumnDragStart(String(key))" @dragstart="onColumnDragStart(String(key))"
@@ -310,7 +314,7 @@ onMounted(() => {
<td <td
v-for="key in visibleReportKeys" v-for="key in visibleReportKeys"
:key="`cell-${idx}-${key}`" :key="`cell-${idx}-${key}`"
class="px-6 py-3 font-mono" class="px-3 py-3 font-mono"
:title="String(getReportCellValue(row, String(key)))" :title="String(getReportCellValue(row, String(key)))"
:style="getReportCellDisplayStyle(String(key))" :style="getReportCellDisplayStyle(String(key))"
> >
@@ -376,7 +380,17 @@ onMounted(() => {
<!-- Statistics Charts --> <!-- Statistics Charts -->
<div v-if="currentTable === 'chat_logs' && usageReport" class="mt-10 border-t border-default pt-10"> <div v-if="currentTable === 'chat_logs' && usageReport" class="mt-10 border-t border-default pt-10">
<h3 class="section-title text-lg mb-6">{{ t('admin.report.usage') }}</h3> <div class="mb-6 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
<h3 class="section-title text-lg">{{ t('admin.report.usage') }}</h3>
<label class="flex items-center gap-2 text-sm text-secondary">
<span class="whitespace-nowrap">{{ t('admin.report.usageRangeLabel') }}</span>
<select v-model="usageRange" class="admin-table-filter-input min-w-[8rem]">
<option v-for="key in usageRangeOptions" :key="key" :value="key">
{{ t(`admin.report.usageRanges.${key}`) }}
</option>
</select>
</label>
</div>
<div class="grid grid-cols-1 md:grid-cols-2 gap-8"> <div class="grid grid-cols-1 md:grid-cols-2 gap-8">
<div class="card p-6"> <div class="card p-6">
<h4 class="text-sm font-bold text-muted uppercase tracking-wider mb-4">{{ t('admin.report.byAgent') }}</h4> <h4 class="text-sm font-bold text-muted uppercase tracking-wider mb-4">{{ t('admin.report.byAgent') }}</h4>
@@ -1,6 +1,8 @@
/** /**
* features/admin/modules/reports/composables/useReportsAdmin.ts * features/admin/modules/reports/composables/useReportsAdmin.ts
* 管理后台报表:多表浏览、筛选、排序、chat_logs 批量删除与用量图表。 * 用途:管理后台报表(多表浏览、筛选、排序、chat_logs 批量删除与带时间范围的用量图表)。
* 依赖:admin.api、useReportLayoutStorage、useOffsetPagination、useMessage、dateTime。
* 逻辑:ReportsPage 调用本 composable;使用分析默认近一月,可切换 7d/30d/90d/180d/365d。
*/ */
import { computed, ref, watch } from 'vue'; import { computed, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
@@ -21,6 +23,7 @@ import type {
ChatLogsLayoutPref, ChatLogsLayoutPref,
ReportColumnConfig, ReportColumnConfig,
SortRule, SortRule,
UsageRangeKey,
UsageReport, UsageReport,
} from '@/features/admin/types/report.types'; } from '@/features/admin/types/report.types';
import type { AdminReportTableId } from '@/features/admin/types/admin.types'; import type { AdminReportTableId } from '@/features/admin/types/admin.types';
@@ -38,6 +41,33 @@ const CHAT_LOGS_REPORT_KEYS = [
const CHAT_LOGS_TABLE_KEYS = ['id', ...CHAT_LOGS_REPORT_KEYS] as const; const CHAT_LOGS_TABLE_KEYS = ['id', ...CHAT_LOGS_REPORT_KEYS] as const;
/**
* 聊天日志列默认宽度:前三列与 Token 收窄,提问/回答留宽。
* @param key - 列字段名
* @returns 像素宽度
*/
const defaultChatLogsColumnWidth = (key: string): number => {
switch (key) {
case 'id':
return 72;
case 'agent_name':
return 120;
case 'username':
return 108;
case 'real_name':
return 108;
case 'created_at':
return 156;
case 'tokens_used':
return 96;
case 'query':
case 'answer':
return 240;
default:
return 160;
}
};
export function useReportsAdmin() { export function useReportsAdmin() {
const { t, locale } = useI18n(); const { t, locale } = useI18n();
const msg = useMessage(); const msg = useMessage();
@@ -47,12 +77,16 @@ export function useReportsAdmin() {
const usageUserPage = ref(1); const usageUserPage = ref(1);
const usageUserPageSize = ref(10); const usageUserPageSize = ref(10);
const usageUserPageSizeOptions = [5, 10, 20, 50]; const usageUserPageSizeOptions = [5, 10, 20, 50];
/** 使用分析时间范围,默认近一月 */
const usageRange = ref<UsageRangeKey>('30d');
const usageRangeOptions: UsageRangeKey[] = ['7d', '30d', '90d', '180d', '365d'];
const loadUsageReport = async (): Promise<void> => { const loadUsageReport = async (): Promise<void> => {
try { try {
usageReport.value = await getAdminUsageReport({ usageReport.value = await getAdminUsageReport({
user_page: usageUserPage.value, user_page: usageUserPage.value,
user_page_size: usageUserPageSize.value, user_page_size: usageUserPageSize.value,
range: usageRange.value,
}); });
const pages = usageReport.value?.user_pages ?? 1; const pages = usageReport.value?.user_pages ?? 1;
if (usageUserPage.value > pages) { if (usageUserPage.value > pages) {
@@ -199,7 +233,7 @@ const initChatLogsColumns = (keys: string[]) => {
const defaults: ReportColumnConfig[] = keys.map((k) => ({ const defaults: ReportColumnConfig[] = keys.map((k) => ({
key: k, key: k,
visible: hideByDefault ? k !== 'id' : true, visible: hideByDefault ? k !== 'id' : true,
width: k === 'id' ? 90 : k === 'tokens_used' ? 120 : 180, width: defaultChatLogsColumnWidth(k),
})); }));
let merged = defaults; let merged = defaults;
@@ -213,7 +247,7 @@ const initChatLogsColumns = (keys: string[]) => {
merged = [...order, ...missing].map((k) => ({ merged = [...order, ...missing].map((k) => ({
key: k, key: k,
visible: savedMap.get(k)?.visible ?? (currentTable.value === 'chat_logs' && k === 'id' ? false : true), visible: savedMap.get(k)?.visible ?? (currentTable.value === 'chat_logs' && k === 'id' ? false : true),
width: savedMap.get(k)?.width ?? (k === 'id' ? 90 : k === 'tokens_used' ? 120 : 180), width: savedMap.get(k)?.width ?? defaultChatLogsColumnWidth(k),
})); }));
if (!Array.isArray(parsed)) { if (!Array.isArray(parsed)) {
chatLogsWrapEnabled.value = !!parsed.wrapEnabled; chatLogsWrapEnabled.value = !!parsed.wrapEnabled;
@@ -826,6 +860,11 @@ watch(usageUserPageSize, () => {
void loadUsageReport(); void loadUsageReport();
}); });
watch(usageRange, () => {
usageUserPage.value = 1;
void loadUsageReport();
});
watch([reportPageSize, sortedTableData], () => { watch([reportPageSize, sortedTableData], () => {
if (reportCurrentPage.value > reportTotalPages.value) { if (reportCurrentPage.value > reportTotalPages.value) {
reportCurrentPage.value = reportTotalPages.value; reportCurrentPage.value = reportTotalPages.value;
@@ -855,6 +894,8 @@ watch([reportPageSize, sortedTableData], () => {
return { return {
usageReport, usageReport,
usageRange,
usageRangeOptions,
usageUserPage, usageUserPage,
usageUserPageSize, usageUserPageSize,
usageUserPageSizeOptions, usageUserPageSizeOptions,
@@ -1,8 +1,8 @@
/** /**
* features/admin/modules/users/UsersPage.vue * features/admin/modules/users/UsersPage.vue
* 用途:用户管理独立页面(服务端筛选分页、批量操作)。 * 用途:用户管理独立页面(服务端筛选分页、用户/部门列排序、批量操作)。
* 依赖:useUsersAdmin、PaginationBar、用户相关 Modal。 * 依赖:useUsersAdmin、SortableTableHeader、PaginationBar、用户相关 Modal。
* 逻辑:路由 /admin/users;列表经 listAdminUsersPage 按页拉取。 * 逻辑:路由 /admin/users;列表经 listAdminUsersPage 按页拉取,表头排序复用 shared 组件。
*/ */
<script setup lang="ts"> <script setup lang="ts">
import { onMounted } from 'vue'; import { onMounted } from 'vue';
@@ -10,6 +10,7 @@ import { useI18n } from 'vue-i18n';
import { Edit, Plus, Trash2, Users } from 'lucide-vue-next'; import { Edit, Plus, Trash2, Users } from 'lucide-vue-next';
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue'; import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
import PaginationBar from '@/shared/components/PaginationBar.vue'; import PaginationBar from '@/shared/components/PaginationBar.vue';
import SortableTableHeader from '@/shared/components/SortableTableHeader.vue';
import BatchEditUserModal from './components/BatchEditUserModal.vue'; import BatchEditUserModal from './components/BatchEditUserModal.vue';
import BatchPermissionModal from './components/BatchPermissionModal.vue'; import BatchPermissionModal from './components/BatchPermissionModal.vue';
import UserFormModal from './components/UserFormModal.vue'; import UserFormModal from './components/UserFormModal.vue';
@@ -24,6 +25,8 @@ const {
isListLoading, isListLoading,
isSaving, isSaving,
userFilters, userFilters,
sortKey,
sortDir,
// hideRejected, // hideRejected,
selectedUserIds, selectedUserIds,
users, users,
@@ -42,6 +45,7 @@ const {
showDeleteConfirmDialog, showDeleteConfirmDialog,
deleteConfirmMessage, deleteConfirmMessage,
loadAll, loadAll,
toggleSort,
openCreateUserModal, openCreateUserModal,
openEditUserModal, openEditUserModal,
saveUser, saveUser,
@@ -156,9 +160,25 @@ onMounted(() => {
@change="toggleAllUsers(users)" @change="toggleAllUsers(users)"
/> />
</th> </th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.user.headers.user') }}</th> <th class="px-6 py-4 text-left text-xs">
<SortableTableHeader
column-key="username"
:label="t('admin.user.headers.user')"
:active-key="sortKey"
:direction="sortDir"
@sort="toggleSort"
/>
</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.user.fields.realName') }}</th> <th class="px-6 py-4 text-left text-xs">{{ t('admin.user.fields.realName') }}</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.user.headers.dept') }}</th> <th class="px-6 py-4 text-left text-xs">
<SortableTableHeader
column-key="department"
:label="t('admin.user.headers.dept')"
:active-key="sortKey"
:direction="sortDir"
@sort="toggleSort"
/>
</th>
<th class="px-6 py-4 text-left text-xs">{{ t('admin.user.headers.role') }}</th> <th class="px-6 py-4 text-left text-xs">{{ t('admin.user.headers.role') }}</th>
<th class="px-6 py-4 text-right text-xs">{{ t('admin.user.headers.actions') }}</th> <th class="px-6 py-4 text-right text-xs">{{ t('admin.user.headers.actions') }}</th>
</tr> </tr>
@@ -1,864 +1,457 @@
/** /**
* features/admin/modules/users/composables/useUsersAdmin.ts * features/admin/modules/users/composables/useUsersAdmin.ts
* 用途:用户管理模块业务逻辑(CRUD、服务端筛选分页、用户/部门列排序、批量操作)。
* 用途:用户管理模块业务逻辑(CRUD、服务端筛选分页、批量操作)。 * 依赖:admin.api、useMessage、useTableSort。
* 逻辑:UsersPage 调用本 composable;列表经 listAdminUsersPage 按页拉取,排序参数随请求下发。
* 依赖:admin.api、useMessage。
* 逻辑:UsersPage 调用本 composable;列表经 listAdminUsersPage 按页拉取。
*/ */
import { computed, ref, watch } from 'vue'; import { computed, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import { import {
batchDeleteAdminUsers, batchDeleteAdminUsers,
batchUpdateAdminPermissions, batchUpdateAdminPermissions,
batchUpdateAdminUsers, batchUpdateAdminUsers,
cleanupRejectedAdminUsers, cleanupRejectedAdminUsers,
createAdminUser, createAdminUser,
listAdminAgents, listAdminAgents,
listAdminDepartments, listAdminDepartments,
listAdminUsersPage, listAdminUsersPage,
updateAdminUser, updateAdminUser,
} from '@/features/admin/api/admin.api'; } from '@/features/admin/api/admin.api';
import { useMessage } from '@/shared/composables/useMessage'; import { useMessage } from '@/shared/composables/useMessage';
import { useTableSort } from '@/shared/composables/useTableSort';
import type { AdminAgentOption, AdminDepartmentRow, AdminUserRow } from '@/features/admin/types/admin.types'; import type { AdminAgentOption, AdminDepartmentRow, AdminUserRow } from '@/features/admin/types/admin.types';
import { import {
createEmptyUserFilters, createEmptyUserFilters,
createEmptyUserForm, createEmptyUserForm,
type BatchEditForm, type BatchEditForm,
type BatchPermissionForm, type BatchPermissionForm,
type UserFilters, type UserFilters,
type UserFormState, type UserFormState,
} from '@/features/admin/types/user.types'; } from '@/features/admin/types/user.types';
const EMAIL_PATTERN = /^[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}$/; const EMAIL_PATTERN = /^[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}$/;
const USER_PAGE_SIZE_OPTIONS = [10, 20, 50, 100] as const; const USER_PAGE_SIZE_OPTIONS = [10, 20, 50, 100] as const;
/** 用户表可排序列:用户名 / 部门(与后端 sort_by 白名单一致) */
export type UserSortKey = 'username' | 'department';
export function useUsersAdmin() { export function useUsersAdmin() {
const { t } = useI18n(); const { t } = useI18n();
const msg = useMessage(); const msg = useMessage();
const users = ref<AdminUserRow[]>([]); const users = ref<AdminUserRow[]>([]);
const agents = ref<AdminAgentOption[]>([]); const agents = ref<AdminAgentOption[]>([]);
const departments = ref<AdminDepartmentRow[]>([]); const departments = ref<AdminDepartmentRow[]>([]);
const isLoading = ref(true); const isLoading = ref(true);
const isListLoading = ref(false); const isListLoading = ref(false);
const isSaving = ref(false); const isSaving = ref(false);
const userFilters = ref<UserFilters>(createEmptyUserFilters()); const userFilters = ref<UserFilters>(createEmptyUserFilters());
/** 用户 / 部门列排序,默认按用户名升序 */
const { sortKey, sortDir, toggleSort: toggleSortBase } = useTableSort<UserSortKey>({
initialKey: 'username',
initialDir: 'asc',
});
const hideRejected = ref(true); const hideRejected = ref(true);
const selectedUserIds = ref<number[]>([]); const selectedUserIds = ref<number[]>([]);
const userPage = ref(1); const userPage = ref(1);
const userPageSize = ref(20); const userPageSize = ref(20);
const usersTotal = ref(0); const usersTotal = ref(0);
const usersPages = ref(1); const usersPages = ref(1);
let userSearchTimer: ReturnType<typeof setTimeout> | null = null; let userSearchTimer: ReturnType<typeof setTimeout> | null = null;
const showUserModal = ref(false); const showUserModal = ref(false);
const editingUser = ref<UserFormState>(createEmptyUserForm()); const editingUser = ref<UserFormState>(createEmptyUserForm());
const showBatchEditModal = ref(false); const showBatchEditModal = ref(false);
const batchEditForm = ref<BatchEditForm>({ department: '', role: '', status: '' }); const batchEditForm = ref<BatchEditForm>({ department: '', role: '', status: '' });
const showBatchPermissionModal = ref(false); const showBatchPermissionModal = ref(false);
const batchPermissionForm = ref<BatchPermissionForm>({ agent_ids: [], action: 'add' }); const batchPermissionForm = ref<BatchPermissionForm>({ agent_ids: [], action: 'add' });
const showDeleteConfirmDialog = ref(false); const showDeleteConfirmDialog = ref(false);
const deleteConfirmMessage = ref(''); const deleteConfirmMessage = ref('');
let deleteConfirmAction: (() => Promise<void> | void) | null = null; let deleteConfirmAction: (() => Promise<void> | void) | null = null;
/** 当前页是否已全部选中 */ /** 当前页是否已全部选中 */
const allPaginatedUsersSelected = computed( const allPaginatedUsersSelected = computed(
() => () =>
users.value.length > 0 users.value.length > 0
&& users.value.every((u) => selectedUserIds.value.includes(u.id)), && users.value.every((u) => selectedUserIds.value.includes(u.id)),
); );
/** /**
* 拉取当前页用户(服务端筛选 + 分页 + 排序)。
* 拉取当前页用户(服务端筛选 + 分页)。 * 核心逻辑:将 userFilters / hideRejected / sortKey / sortDir 传给 listAdminUsersPage。
* 核心逻辑:将 userFilters / hideRejected 传给 listAdminUsersPage,写回 items 与分页元数据。
*/ */
const loadUsers = async (): Promise<void> => { const loadUsers = async (): Promise<void> => {
isListLoading.value = true; isListLoading.value = true;
try { try {
const data = await listAdminUsersPage({ const data = await listAdminUsersPage({
page: userPage.value, page: userPage.value,
pageSize: userPageSize.value, pageSize: userPageSize.value,
username: userFilters.value.username, username: userFilters.value.username,
real_name: userFilters.value.real_name, real_name: userFilters.value.real_name,
department: userFilters.value.department, department: userFilters.value.department,
hideRejected: hideRejected.value, hideRejected: hideRejected.value,
sortBy: sortKey.value,
sortDir: sortDir.value,
}); });
users.value = data.items; users.value = data.items;
usersTotal.value = data.total; usersTotal.value = data.total;
userPage.value = data.page; userPage.value = data.page;
usersPages.value = data.pages; usersPages.value = data.pages;
} catch (e) { } catch (e) {
console.error('Error loading users:', e); console.error('Error loading users:', e);
users.value = []; users.value = [];
usersTotal.value = 0; usersTotal.value = 0;
usersPages.value = 1; usersPages.value = 1;
} finally { } finally {
isListLoading.value = false; isListLoading.value = false;
} }
}; };
/** /**
* 重置页码并刷新列表;若页码已是 1 则直接请求。 * 重置页码并刷新列表;若页码已是 1 则直接请求。
* @param resetPage - 为 true 时将 page 置 1 * @param resetPage - 为 true 时将 page 置 1
*/ */
const scheduleLoadUsers = (resetPage = false): void => { const scheduleLoadUsers = (resetPage = false): void => {
if (resetPage) { if (resetPage) {
if (userPage.value !== 1) { if (userPage.value !== 1) {
userPage.value = 1; userPage.value = 1;
return; return;
} }
} }
void loadUsers(); void loadUsers();
}; };
const loadAgents = async (): Promise<void> => { const loadAgents = async (): Promise<void> => {
try { try {
agents.value = await listAdminAgents(); agents.value = await listAdminAgents();
} catch (e) { } catch (e) {
console.error('Error loading agents:', e); console.error('Error loading agents:', e);
agents.value = []; agents.value = [];
} }
}; };
const loadDepartments = async (): Promise<void> => { const loadDepartments = async (): Promise<void> => {
try { try {
departments.value = await listAdminDepartments(); departments.value = await listAdminDepartments();
} catch (e) { } catch (e) {
console.error('Error loading departments:', e); console.error('Error loading departments:', e);
departments.value = []; departments.value = [];
} }
}; };
const loadAll = async (): Promise<void> => { const loadAll = async (): Promise<void> => {
isLoading.value = true; isLoading.value = true;
await Promise.all([loadUsers(), loadAgents(), loadDepartments()]); await Promise.all([loadUsers(), loadAgents(), loadDepartments()]);
isLoading.value = false; isLoading.value = false;
}; };
watch(userPage, () => { watch(userPage, () => {
void loadUsers(); void loadUsers();
}); });
watch(userPageSize, () => { watch(userPageSize, () => {
scheduleLoadUsers(true); scheduleLoadUsers(true);
}); });
watch([userFilters, hideRejected], () => { watch([userFilters, hideRejected], () => {
if (userSearchTimer) clearTimeout(userSearchTimer); if (userSearchTimer) clearTimeout(userSearchTimer);
userSearchTimer = setTimeout(() => { userSearchTimer = setTimeout(() => {
scheduleLoadUsers(true); scheduleLoadUsers(true);
}, 300); }, 300);
}, { deep: true }); }, { deep: true });
const openDeleteConfirm = (message: string, action: () => Promise<void> | void): void => { const openDeleteConfirm = (message: string, action: () => Promise<void> | void): void => {
deleteConfirmMessage.value = message; deleteConfirmMessage.value = message;
deleteConfirmAction = action; deleteConfirmAction = action;
showDeleteConfirmDialog.value = true; showDeleteConfirmDialog.value = true;
}; };
const closeDeleteConfirm = (): void => { const closeDeleteConfirm = (): void => {
showDeleteConfirmDialog.value = false; showDeleteConfirmDialog.value = false;
deleteConfirmAction = null; deleteConfirmAction = null;
}; };
/** /**
* 执行待确认的删除操作。 * 执行待确认的删除操作。
* 核心逻辑:先快照 action 并立即关闭弹窗,再 await 删除与刷新,避免异步完成前弹窗无法关闭。 * 核心逻辑:先快照 action 并立即关闭弹窗,再 await 删除与刷新,避免异步完成前弹窗无法关闭。
*/ */
const confirmDelete = async (): Promise<void> => { const confirmDelete = async (): Promise<void> => {
const action = deleteConfirmAction; const action = deleteConfirmAction;
closeDeleteConfirm(); closeDeleteConfirm();
if (!action) return; if (!action) return;
await action(); await action();
}; };
const openCreateUserModal = (): void => { const openCreateUserModal = (): void => {
editingUser.value = createEmptyUserForm(); editingUser.value = createEmptyUserForm();
showUserModal.value = true; showUserModal.value = true;
}; };
const openEditUserModal = (user: AdminUserRow): void => { const openEditUserModal = (user: AdminUserRow): void => {
editingUser.value = { editingUser.value = {
id: user.id, id: user.id,
username: user.username, username: user.username,
email: user.email, email: user.email,
department: user.department || '', department: user.department || '',
role: user.role, role: user.role,
password: '', password: '',
real_name: user.real_name || '', real_name: user.real_name || '',
employee_id: user.employee_id || '', employee_id: user.employee_id || '',
phone_number: user.phone_number || '', phone_number: user.phone_number || '',
feature_permissions: { feature_permissions: {
training_hr_manage: Boolean(user.feature_permissions?.training_hr_manage), training_hr_manage: Boolean(user.feature_permissions?.training_hr_manage),
}, },
agent_ids: user.agent_ids || [], agent_ids: user.agent_ids || [],
}; };
showUserModal.value = true; showUserModal.value = true;
}; };
const saveUser = async (): Promise<void> => { const saveUser = async (): Promise<void> => {
const isCreate = !editingUser.value.id; const isCreate = !editingUser.value.id;
if (isCreate) { if (isCreate) {
if (!(editingUser.value.real_name || '').trim()) { if (!(editingUser.value.real_name || '').trim()) {
msg.warning(t('admin.user.msgs.realNameRequired')); msg.warning(t('admin.user.msgs.realNameRequired'));
return; return;
} }
if (!(editingUser.value.employee_id || '').trim()) { if (!(editingUser.value.employee_id || '').trim()) {
msg.warning(t('admin.user.msgs.employeeIdRequired')); msg.warning(t('admin.user.msgs.employeeIdRequired'));
return; return;
} }
if (!(editingUser.value.phone_number || '').trim()) { if (!(editingUser.value.phone_number || '').trim()) {
msg.warning(t('admin.user.msgs.phoneRequired')); msg.warning(t('admin.user.msgs.phoneRequired'));
return; return;
} }
if (!(editingUser.value.username || '').trim()) { if (!(editingUser.value.username || '').trim()) {
msg.warning(t('admin.user.msgs.usernameRequired')); msg.warning(t('admin.user.msgs.usernameRequired'));
return; return;
} }
const email = (editingUser.value.email || '').trim(); const email = (editingUser.value.email || '').trim();
if (!email) { if (!email) {
msg.warning(t('admin.user.msgs.emailRequired')); msg.warning(t('admin.user.msgs.emailRequired'));
return; return;
} }
if (!EMAIL_PATTERN.test(email)) { if (!EMAIL_PATTERN.test(email)) {
msg.warning(t('admin.user.msgs.invalidEmail')); msg.warning(t('admin.user.msgs.invalidEmail'));
return; return;
} }
if (!(editingUser.value.password || '').trim()) { if (!(editingUser.value.password || '').trim()) {
msg.warning(t('admin.user.msgs.passwordRequired')); msg.warning(t('admin.user.msgs.passwordRequired'));
return; return;
} }
} else { } else {
if (!editingUser.value.username) { if (!editingUser.value.username) {
msg.warning(t('admin.user.msgs.usernameRequired')); msg.warning(t('admin.user.msgs.usernameRequired'));
return; return;
} }
const email = (editingUser.value.email || '').trim(); const email = (editingUser.value.email || '').trim();
if (email && !EMAIL_PATTERN.test(email)) { if (email && !EMAIL_PATTERN.test(email)) {
msg.warning(t('admin.user.msgs.invalidEmail')); msg.warning(t('admin.user.msgs.invalidEmail'));
return; return;
} }
} }
isSaving.value = true; isSaving.value = true;
try { try {
if (editingUser.value.id) { if (editingUser.value.id) {
await updateAdminUser(editingUser.value.id, { await updateAdminUser(editingUser.value.id, {
email: editingUser.value.email, email: editingUser.value.email,
department: editingUser.value.department, department: editingUser.value.department,
role: editingUser.value.role, role: editingUser.value.role,
password: editingUser.value.password || undefined, password: editingUser.value.password || undefined,
real_name: editingUser.value.real_name, real_name: editingUser.value.real_name,
employee_id: editingUser.value.employee_id, employee_id: editingUser.value.employee_id,
phone_number: editingUser.value.phone_number, phone_number: editingUser.value.phone_number,
feature_permissions: editingUser.value.feature_permissions, feature_permissions: editingUser.value.feature_permissions,
agent_ids: editingUser.value.agent_ids, agent_ids: editingUser.value.agent_ids,
}); });
} else { } else {
await createAdminUser({ await createAdminUser({
username: editingUser.value.username, username: editingUser.value.username,
email: editingUser.value.email, email: editingUser.value.email,
department: editingUser.value.department, department: editingUser.value.department,
role: editingUser.value.role, role: editingUser.value.role,
password: editingUser.value.password, password: editingUser.value.password,
real_name: editingUser.value.real_name, real_name: editingUser.value.real_name,
employee_id: editingUser.value.employee_id, employee_id: editingUser.value.employee_id,
phone_number: editingUser.value.phone_number, phone_number: editingUser.value.phone_number,
feature_permissions: editingUser.value.feature_permissions, feature_permissions: editingUser.value.feature_permissions,
agent_ids: editingUser.value.agent_ids, agent_ids: editingUser.value.agent_ids,
}); });
} }
await loadUsers(); await loadUsers();
showUserModal.value = false; showUserModal.value = false;
} catch (e) { } catch (e) {
console.error(e); console.error(e);
msg.error((e as Error).message || t('admin.msg.failed')); msg.error((e as Error).message || t('admin.msg.failed'));
} finally { } finally {
isSaving.value = false; isSaving.value = false;
} }
}; };
const cleanRejectedUsers = async (): Promise<void> => { const cleanRejectedUsers = async (): Promise<void> => {
openDeleteConfirm(t('admin.user.confirmClean'), async () => { openDeleteConfirm(t('admin.user.confirmClean'), async () => {
try { try {
const data = await cleanupRejectedAdminUsers(); const data = await cleanupRejectedAdminUsers();
msg.success(t('admin.msg.batchDeleteResult', { count: data.deleted_count })); msg.success(t('admin.msg.batchDeleteResult', { count: data.deleted_count }));
await loadUsers(); await loadUsers();
} catch (e) { } catch (e) {
console.error(e); console.error(e);
msg.error((e as Error).message || t('admin.msg.requestFailed')); msg.error((e as Error).message || t('admin.msg.requestFailed'));
} }
}); });
}; };
const batchDeleteUsers = async (): Promise<void> => { const batchDeleteUsers = async (): Promise<void> => {
if (selectedUserIds.value.length === 0) return; if (selectedUserIds.value.length === 0) return;
const targetUserIds = [...selectedUserIds.value]; const targetUserIds = [...selectedUserIds.value];
openDeleteConfirm(t('admin.user.confirmBatchDelete', { count: targetUserIds.length }), async () => { openDeleteConfirm(t('admin.user.confirmBatchDelete', { count: targetUserIds.length }), async () => {
try { try {
const data = await batchDeleteAdminUsers(targetUserIds); const data = await batchDeleteAdminUsers(targetUserIds);
msg.success(t('admin.msg.batchDeleteResult', { count: data.deleted_count })); msg.success(t('admin.msg.batchDeleteResult', { count: data.deleted_count }));
selectedUserIds.value = []; selectedUserIds.value = [];
await loadUsers(); await loadUsers();
} catch (e) { } catch (e) {
console.error(e); console.error(e);
msg.error((e as Error).message || t('admin.msg.requestFailed')); msg.error((e as Error).message || t('admin.msg.requestFailed'));
} }
}); });
}; };
const toggleUserSelection = (userId: number): void => { const toggleUserSelection = (userId: number): void => {
const index = selectedUserIds.value.indexOf(userId); const index = selectedUserIds.value.indexOf(userId);
if (index === -1) selectedUserIds.value.push(userId); if (index === -1) selectedUserIds.value.push(userId);
else selectedUserIds.value.splice(index, 1); else selectedUserIds.value.splice(index, 1);
}; };
/**
* 切换当前页用户的全选状态,保留其他页已选中的用户。
* 核心逻辑:若本页已全部选中则仅取消本页 ID;否则合并本页 ID 到 selectedUserIds。
* @param rows - 当前页用户行
*/
const toggleAllUsers = (rows: AdminUserRow[]): void => {
const rowIds = rows.map((u) => u.id);
const allSelected = rowIds.length > 0 && rowIds.every((id) => selectedUserIds.value.includes(id));
if (allSelected) {
selectedUserIds.value = selectedUserIds.value.filter((id) => !rowIds.includes(id));
} else {
selectedUserIds.value = [...new Set([...selectedUserIds.value, ...rowIds])];
}
};
const openBatchEditModal = (): void => {
if (selectedUserIds.value.length === 0) return;
batchEditForm.value = { department: '', role: '', status: '' };
showBatchEditModal.value = true;
};
const openBatchPermissionModal = (): void => {
if (selectedUserIds.value.length === 0) return;
batchPermissionForm.value = { agent_ids: [], action: 'add' };
showBatchPermissionModal.value = true;
};
const submitBatchEdit = async (): Promise<void> => {
isSaving.value = true;
try {
const data: Record<string, string> = {};
if (batchEditForm.value.department) data.department = batchEditForm.value.department;
if (batchEditForm.value.role) data.role = batchEditForm.value.role;
if (batchEditForm.value.status) data.status = batchEditForm.value.status;
if (Object.keys(data).length === 0) {
msg.warning(t('admin.msg.enterOneField'));
return;
}
await batchUpdateAdminUsers(selectedUserIds.value, data);
await loadUsers();
showBatchEditModal.value = false;
selectedUserIds.value = [];
} catch (e) {
console.error(e);
msg.error((e as Error).message || t('admin.msg.batchUpdateFailed'));
} finally {
isSaving.value = false;
}
};
const submitBatchPermission = async (): Promise<void> => {
if (batchPermissionForm.value.agent_ids.length === 0) {
msg.warning(t('admin.perm.msg.selectAgent'));
return;
}
isSaving.value = true;
try {
await batchUpdateAdminPermissions({
user_ids: selectedUserIds.value,
agent_ids: batchPermissionForm.value.agent_ids,
action: batchPermissionForm.value.action,
});
await loadUsers();
showBatchPermissionModal.value = false;
selectedUserIds.value = [];
} catch (e) {
console.error(e);
msg.error((e as Error).message || t('admin.msg.batchPermissionUpdateFailed'));
} finally {
isSaving.value = false;
}
};
/** /**
* 切换用户/部门列排序并重新拉取第一页。
* 切换当前页用户的全选状态,保留其他页已选中的用户。 * @param key - username | department
* 核心逻辑:若本页已全部选中则仅取消本页 ID;否则合并本页 ID 到 selectedUserIds。
* @param rows - 当前页用户行
*/ */
const toggleSort = (key: UserSortKey): void => {
const toggleAllUsers = (rows: AdminUserRow[]): void => { toggleSortBase(key);
scheduleLoadUsers(true);
const rowIds = rows.map((u) => u.id);
const allSelected = rowIds.length > 0 && rowIds.every((id) => selectedUserIds.value.includes(id));
if (allSelected) {
selectedUserIds.value = selectedUserIds.value.filter((id) => !rowIds.includes(id));
} else {
selectedUserIds.value = [...new Set([...selectedUserIds.value, ...rowIds])];
}
}; };
const openBatchEditModal = (): void => {
if (selectedUserIds.value.length === 0) return;
batchEditForm.value = { department: '', role: '', status: '' };
showBatchEditModal.value = true;
};
const openBatchPermissionModal = (): void => {
if (selectedUserIds.value.length === 0) return;
batchPermissionForm.value = { agent_ids: [], action: 'add' };
showBatchPermissionModal.value = true;
};
const submitBatchEdit = async (): Promise<void> => {
isSaving.value = true;
try {
const data: Record<string, string> = {};
if (batchEditForm.value.department) data.department = batchEditForm.value.department;
if (batchEditForm.value.role) data.role = batchEditForm.value.role;
if (batchEditForm.value.status) data.status = batchEditForm.value.status;
if (Object.keys(data).length === 0) {
msg.warning(t('admin.msg.enterOneField'));
return;
}
await batchUpdateAdminUsers(selectedUserIds.value, data);
await loadUsers();
showBatchEditModal.value = false;
selectedUserIds.value = [];
} catch (e) {
console.error(e);
msg.error((e as Error).message || t('admin.msg.batchUpdateFailed'));
} finally {
isSaving.value = false;
}
};
const submitBatchPermission = async (): Promise<void> => {
if (batchPermissionForm.value.agent_ids.length === 0) {
msg.warning(t('admin.perm.msg.selectAgent'));
return;
}
isSaving.value = true;
try {
await batchUpdateAdminPermissions({
user_ids: selectedUserIds.value,
agent_ids: batchPermissionForm.value.agent_ids,
action: batchPermissionForm.value.action,
});
await loadUsers();
showBatchPermissionModal.value = false;
selectedUserIds.value = [];
} catch (e) {
console.error(e);
msg.error((e as Error).message || t('admin.msg.batchPermissionUpdateFailed'));
} finally {
isSaving.value = false;
}
};
return { return {
users, users,
agents, agents,
departments, departments,
isLoading, isLoading,
isListLoading, isListLoading,
isSaving, isSaving,
userFilters, userFilters,
sortKey,
sortDir,
hideRejected, hideRejected,
selectedUserIds, selectedUserIds,
usersTotal, usersTotal,
userPage, userPage,
userPageSize, userPageSize,
userPageSizeOptions: USER_PAGE_SIZE_OPTIONS, userPageSizeOptions: USER_PAGE_SIZE_OPTIONS,
usersPages, usersPages,
allPaginatedUsersSelected, allPaginatedUsersSelected,
showUserModal, showUserModal,
editingUser, editingUser,
showBatchEditModal, showBatchEditModal,
batchEditForm, batchEditForm,
showBatchPermissionModal, showBatchPermissionModal,
batchPermissionForm, batchPermissionForm,
showDeleteConfirmDialog, showDeleteConfirmDialog,
deleteConfirmMessage, deleteConfirmMessage,
loadAll, loadAll,
toggleSort,
openCreateUserModal, openCreateUserModal,
openEditUserModal, openEditUserModal,
saveUser, saveUser,
cleanRejectedUsers, cleanRejectedUsers,
batchDeleteUsers, batchDeleteUsers,
toggleUserSelection, toggleUserSelection,
toggleAllUsers, toggleAllUsers,
openBatchEditModal, openBatchEditModal,
openBatchPermissionModal, openBatchPermissionModal,
submitBatchEdit, submitBatchEdit,
submitBatchPermission, submitBatchPermission,
closeDeleteConfirm, closeDeleteConfirm,
confirmDelete, confirmDelete,
}; };
} }
@@ -1,7 +1,10 @@
/** /**
* features/admin/types/department.types.ts * features/admin/types/department.types.ts
* 部门管理表单类型。 * 用途:部门管理表单状态与行数据转换。
* 依赖:AdminDepartmentRow(admin.types)。
* 逻辑:useDepartmentsAdmin / DepartmentFormModal 共用本类型与工厂方法。
*/ */
import type { AdminDepartmentRow } from '@/features/admin/types/admin.types';
export interface DepartmentFormState { export interface DepartmentFormState {
id?: number; id?: number;
@@ -11,9 +14,26 @@ export interface DepartmentFormState {
description?: string; description?: string;
} }
/**
* 创建空白部门表单(用于「添加部门」弹窗)。
* @returns 空表单初始值
*/
export const createEmptyDepartmentForm = (): DepartmentFormState => ({ export const createEmptyDepartmentForm = (): DepartmentFormState => ({
name: '', name: '',
code: '', code: '',
company: '', company: '',
description: '', description: '',
}); });
/**
* 将列表行转为编辑表单状态。
* @param dept - 部门列表行
* @returns 可绑定到弹窗的表单对象
*/
export const departmentRowToForm = (dept: AdminDepartmentRow): DepartmentFormState => ({
id: dept.id,
name: dept.name,
code: dept.code || '',
company: dept.company || '',
description: dept.description || '',
});
@@ -1,10 +1,17 @@
/** /**
* features/admin/types/report.types.ts * features/admin/types/report.types.ts
* 报表模块类型。 * 用途:报表模块类型(使用分析、列配置、排序规则)。
* 依赖:无。
* 逻辑:useReportsAdmin / admin.api 共用。
*/ */
/** 使用分析时间范围(与后端 USAGE_RANGE_DAYS 一致) */
export type UsageRangeKey = '7d' | '30d' | '90d' | '180d' | '365d';
export interface UsageReport { export interface UsageReport {
total: number; total: number;
/** 当前统计时间范围 */
range?: UsageRangeKey;
by_user: { username: string; count: number }[]; by_user: { username: string; count: number }[];
by_agent: { agent: string; count: number }[]; by_agent: { agent: string; count: number }[];
by_day?: { date: string; count: number }[]; by_day?: { date: string; count: number }[];
@@ -3,7 +3,9 @@
* features/chat/components/TrainingWorkspacePanel.vue * features/chat/components/TrainingWorkspacePanel.vue
* 用途:在培训 Agent 的聊天页顶部提供“员工培训 + 培训管理”一体化工作区。 * 用途:在培训 Agent 的聊天页顶部提供“员工培训 + 培训管理”一体化工作区。
* 依赖:useTrainingWorkspace、lucide 图标、聊天页 currentAgent/currentUser。 * 依赖:useTrainingWorkspace、lucide 图标、聊天页 currentAgent/currentUser。
* 逻辑:只在培训 Agent 下渲染;员工与 HR 管理员首次进入默认展开工作区,但新建/切换会话后保持收起,避免聊天过程中被自动展开打断。 * 逻辑:只在培训 Agent 下渲染;员工与 HR 管理员首次进入默认展开工作区,
* 收起态下点击“员工培训 / 培训管理 / 展开工作区”会直接展开到对应工作区;
* 新建/切换会话后统一回到聊天页,避免聊天过程中被自动展开打断。
*/ */
import { computed, reactive, ref, watch, type ShallowUnwrapRef } from 'vue'; import { computed, reactive, ref, watch, type ShallowUnwrapRef } from 'vue';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
@@ -94,6 +96,33 @@ const setWorkspaceExpanded = (expanded: boolean, manual = false) => {
} }
}; };
/**
* 从聊天页顶部入口切换到指定培训工作区,并立即展开工作区内容。
* AI 触发时机:当用户在 chat 主页面手动点击“员工培训 / 培训管理 / 展开工作区”时,
* 不能只切换 tab 高亮,必须同步展开对应工作区,避免用户误以为点击无效。
*/
const openWorkspaceView = (view: typeof workspace.activeView) => {
workspace.activeView = view;
setWorkspaceExpanded(true, true);
};
/**
* 收起培训工作区并回到纯聊天页面。
* AI 触发时机:点击“收起工作区”时,必须立即恢复聊天消息区与输入栏,而不是仅折叠局部内容。
*/
const collapseToChatPage = () => {
setWorkspaceExpanded(false, true);
};
/**
* 展开当前已选中的培训工作区。
* AI 触发时机:当用户已在收起态选定某个 tab 后点击“展开工作区”,
* 应沿用当前 activeView 打开对应面板,而不是切回默认视图。
*/
const expandCurrentWorkspace = () => {
setWorkspaceExpanded(true, true);
};
const currentAnswerLabel = computed(() => { const currentAnswerLabel = computed(() => {
const question = workspace.currentQuestion; const question = workspace.currentQuestion;
if (!question) return ''; if (!question) return '';
@@ -222,7 +251,7 @@ const handleStageCardClick = (stageKey: string) => {
type="button" type="button"
class="rounded-full px-3 py-1.5 text-xs font-medium transition" class="rounded-full px-3 py-1.5 text-xs font-medium transition"
:class="workspace.activeView === 'learner' ? 'bg-brand-600 text-white' : 'bg-surface-soft text-secondary hover:bg-slate-100'" :class="workspace.activeView === 'learner' ? 'bg-brand-600 text-white' : 'bg-surface-soft text-secondary hover:bg-slate-100'"
@click="workspace.activeView = 'learner'" @click="openWorkspaceView('learner')"
> >
{{ $t('chat.training.tabs.learner') }} {{ $t('chat.training.tabs.learner') }}
</button> </button>
@@ -231,7 +260,7 @@ const handleStageCardClick = (stageKey: string) => {
type="button" type="button"
class="rounded-full px-3 py-1.5 text-xs font-medium transition" class="rounded-full px-3 py-1.5 text-xs font-medium transition"
:class="workspace.activeView === 'admin' ? 'bg-brand-600 text-white' : 'bg-surface-soft text-secondary hover:bg-slate-100'" :class="workspace.activeView === 'admin' ? 'bg-brand-600 text-white' : 'bg-surface-soft text-secondary hover:bg-slate-100'"
@click="workspace.activeView = 'admin'" @click="openWorkspaceView('admin')"
> >
{{ $t('chat.training.tabs.admin') }} {{ $t('chat.training.tabs.admin') }}
</button> </button>
@@ -260,7 +289,7 @@ const handleStageCardClick = (stageKey: string) => {
<button <button
type="button" type="button"
class="inline-flex h-9 items-center gap-2 rounded-xl border border-default bg-white px-3.5 text-xs font-medium leading-none text-secondary transition hover:bg-surface-soft" class="inline-flex h-9 items-center gap-2 rounded-xl border border-default bg-white px-3.5 text-xs font-medium leading-none text-secondary transition hover:bg-surface-soft"
@click="setWorkspaceExpanded(true, true)" @click="expandCurrentWorkspace"
> >
<ChevronDown class="h-4 w-4 shrink-0" /> <ChevronDown class="h-4 w-4 shrink-0" />
<span class="leading-none">{{ $t('chat.training.actions.expandWorkspace') }}</span> <span class="leading-none">{{ $t('chat.training.actions.expandWorkspace') }}</span>
@@ -337,7 +366,7 @@ const handleStageCardClick = (stageKey: string) => {
<button <button
type="button" type="button"
class="inline-flex h-9 items-center gap-2 rounded-xl border border-default bg-white px-3.5 text-xs font-medium leading-none text-secondary transition hover:bg-surface-soft" class="inline-flex h-9 items-center gap-2 rounded-xl border border-default bg-white px-3.5 text-xs font-medium leading-none text-secondary transition hover:bg-surface-soft"
@click="setWorkspaceExpanded(false, true)" @click="collapseToChatPage"
> >
<ChevronUp class="h-4 w-4 shrink-0" /> <ChevronUp class="h-4 w-4 shrink-0" />
<span class="leading-none">{{ $t('chat.training.actions.collapseWorkspace') }}</span> <span class="leading-none">{{ $t('chat.training.actions.collapseWorkspace') }}</span>
@@ -628,7 +628,10 @@ defineProps<{
<DeleteConfirmDialog <DeleteConfirmDialog
v-model="kb.showDeleteConfirmDialog" v-model="kb.showDeleteConfirmDialog"
:title="kb.deleteConfirmTitle"
:message="kb.deleteConfirmMessage" :message="kb.deleteConfirmMessage"
:confirm-text="kb.deleteConfirmText"
:confirm-tone="kb.deleteConfirmTone"
@confirm="kb.handleDeleteConfirm" @confirm="kb.handleDeleteConfirm"
@cancel="kb.closeDeleteConfirmDialog" @cancel="kb.closeDeleteConfirmDialog"
/> />
@@ -1,6 +1,8 @@
/** /**
* features/kb/composables/kb-workspace/kb-workspace.state.ts * features/kb/composables/kb-workspace/kb-workspace.state.ts
* 作业面共享响应式状态:各子 composable 通过同一 state 读写,避免重复 ref。 * 用途:作业面共享响应式状态;各子 composable 通过同一 state 读写,避免重复 ref。
* 依赖:vue-router、vue-i18n、auth、kb.api 类型、kb-workspace.types。
* 逻辑:createKbWorkspaceState 产出全部 ref;含公共确认弹窗(删除/上传路径等)辅助方法。
*/ */
import { computed, ref } from 'vue'; import { computed, ref } from 'vue';
import { useRouter } from 'vue-router'; import { useRouter } from 'vue-router';
@@ -57,6 +59,9 @@ export function createKbWorkspaceState(options: CreateKbWorkspaceStateOptions =
const showPathUploadHistoryModal = ref(false); const showPathUploadHistoryModal = ref(false);
const showDeleteConfirmDialog = ref(false); const showDeleteConfirmDialog = ref(false);
const deleteConfirmMessage = ref(''); const deleteConfirmMessage = ref('');
const deleteConfirmTitle = ref('');
const deleteConfirmText = ref('');
const deleteConfirmTone = ref<'danger' | 'primary'>('danger');
let pendingDeleteAction: (() => Promise<void> | void) | null = null; let pendingDeleteAction: (() => Promise<void> | void) | null = null;
const showPathUploadDetails = ref(false); const showPathUploadDetails = ref(false);
const fileInputRef = ref<HTMLInputElement | null>(null); const fileInputRef = ref<HTMLInputElement | null>(null);
@@ -114,11 +119,27 @@ export function createKbWorkspaceState(options: CreateKbWorkspaceStateOptions =
items: [], items: [],
}); });
/**
* 打开公共确认弹窗(删除 / 上传路径等场景复用)。
* @param message - 正文
* @param onConfirm - 确认回调
* @param options.title - 标题;空则用删除默认文案
* @param options.confirmText - 确认按钮文案
* @param options.confirmTone - danger 删除 / primary 非破坏性确认
*/
const openDeleteConfirmDialog = ( const openDeleteConfirmDialog = (
message: string, message: string,
onConfirm: () => Promise<void> | void, onConfirm: () => Promise<void> | void,
options?: {
title?: string;
confirmText?: string;
confirmTone?: 'danger' | 'primary';
},
) => { ) => {
deleteConfirmMessage.value = message; deleteConfirmMessage.value = message;
deleteConfirmTitle.value = options?.title || '';
deleteConfirmText.value = options?.confirmText || '';
deleteConfirmTone.value = options?.confirmTone || 'danger';
pendingDeleteAction = onConfirm; pendingDeleteAction = onConfirm;
showDeleteConfirmDialog.value = true; showDeleteConfirmDialog.value = true;
}; };
@@ -126,6 +147,9 @@ export function createKbWorkspaceState(options: CreateKbWorkspaceStateOptions =
const closeDeleteConfirmDialog = () => { const closeDeleteConfirmDialog = () => {
showDeleteConfirmDialog.value = false; showDeleteConfirmDialog.value = false;
deleteConfirmMessage.value = ''; deleteConfirmMessage.value = '';
deleteConfirmTitle.value = '';
deleteConfirmText.value = '';
deleteConfirmTone.value = 'danger';
pendingDeleteAction = null; pendingDeleteAction = null;
}; };
@@ -170,6 +194,9 @@ export function createKbWorkspaceState(options: CreateKbWorkspaceStateOptions =
showPathUploadHistoryModal, showPathUploadHistoryModal,
showDeleteConfirmDialog, showDeleteConfirmDialog,
deleteConfirmMessage, deleteConfirmMessage,
deleteConfirmTitle,
deleteConfirmText,
deleteConfirmTone,
showPathUploadDetails, showPathUploadDetails,
fileInputRef, fileInputRef,
pathUploadInputRef, pathUploadInputRef,
@@ -1,6 +1,8 @@
/** /**
* features/kb/composables/kb-workspace/useKbWorkspacePathUpload.ts * features/kb/composables/kb-workspace/useKbWorkspacePathUpload.ts
* 路径上传:选文件、分批 job、轮询进度与历史批次操作。 * 用途:路径上传编排——选目录、分批 job、轮询进度与历史批次操作。
* 依赖:kb.api、kb-path-upload.utils、DeleteConfirmDialog(经 state.openDeleteConfirmDialog)。
* 逻辑:优先 showDirectoryPicker 避免浏览器原生目录确认;回退 webkitdirectory;确认后写入待上传清单。
*/ */
import type { KbJob } from '../../api/kb.api'; import type { KbJob } from '../../api/kb.api';
import { import {
@@ -169,21 +171,25 @@ export function useKbWorkspacePathUpload(
resetPathUploadDraft(); resetPathUploadDraft();
}; };
const triggerPathUploadSelection = () => { /**
pathUploadInputRef.value?.click(); * 将 File 列表合并进待上传清单(按相对路径去重)。
}; * @param files - 目录遍历得到的文件
* @param getRelativePath - 取相对路径;缺省用 webkitRelativePath / name
const handlePathFilesSelected = (event: Event) => { */
const input = event.target as HTMLInputElement; const appendPathUploadFiles = (
const files = Array.from(input.files || []); files: File[],
if (!files.length) { getRelativePath?: (file: File) => string,
input.value = ''; ) => {
return; if (!files.length) return;
}
const existing = new Set(pathUploadSelectedFiles.value.map((item) => item.displayPath)); const existing = new Set(pathUploadSelectedFiles.value.map((item) => item.displayPath));
const nextItems = files.flatMap((file, index) => { const nextItems = files.flatMap((file, index) => {
const relativePath = (file as File & { webkitRelativePath?: string }).webkitRelativePath || file.name; const relativePath = (
if (existing.has(relativePath)) return []; getRelativePath?.(file)
|| (file as File & { webkitRelativePath?: string }).webkitRelativePath
|| file.name
).replace(/\\/g, '/');
if (!relativePath || existing.has(relativePath)) return [];
existing.add(relativePath);
const rootLabel = relativePath.includes('/') ? relativePath.split('/')[0] || file.name : file.name; const rootLabel = relativePath.includes('/') ? relativePath.split('/')[0] || file.name : file.name;
return [{ return [{
key: `${Date.now()}-${index}-${relativePath}`, key: `${Date.now()}-${index}-${relativePath}`,
@@ -192,9 +198,111 @@ export function useKbWorkspacePathUpload(
rootLabel, rootLabel,
}]; }];
}); });
if (!nextItems.length) return;
pathUploadSelectedFiles.value = [...pathUploadSelectedFiles.value, ...nextItems]; pathUploadSelectedFiles.value = [...pathUploadSelectedFiles.value, ...nextItems];
pathUploadDraftText.value = pathUploadSelectedFiles.value.map((item) => item.displayPath).join('\n'); pathUploadDraftText.value = pathUploadSelectedFiles.value.map((item) => item.displayPath).join('\n');
};
/**
* 递归读取 File System Access API 目录句柄下的全部文件。
*/
const collectFilesFromDirectoryHandle = async (
handle: FileSystemDirectoryHandle,
parentPath = '',
): Promise<File[]> => {
const files: File[] = [];
// File System Access API:DirectoryHandle 可异步迭代子项
for await (const entry of (handle as any).values() as AsyncIterable<FileSystemHandle>) {
const entryPath = parentPath ? `${parentPath}/${entry.name}` : entry.name;
if (entry.kind === 'file') {
const file = await (entry as FileSystemFileHandle).getFile();
Object.defineProperty(file, 'webkitRelativePath', {
configurable: true,
value: entryPath,
});
files.push(file);
} else if (entry.kind === 'directory') {
files.push(...await collectFilesFromDirectoryHandle(entry as FileSystemDirectoryHandle, entryPath));
}
}
return files;
};
/**
* 打开目录选择器;优先 showDirectoryPicker(无 Windows 原生上传确认),
* 不支持时回退隐藏 input[webkitdirectory]。
* 选完后用公共 DeleteConfirmDialog 二次确认再写入清单。
*/
const triggerPathUploadSelection = async () => {
const picker = (window as Window & {
showDirectoryPicker?: (options?: { mode?: 'read' | 'readwrite' }) => Promise<FileSystemDirectoryHandle>;
}).showDirectoryPicker;
if (typeof picker === 'function') {
try {
const dirHandle = await picker({ mode: 'read' });
const files = await collectFilesFromDirectoryHandle(dirHandle, dirHandle.name);
if (!files.length) {
feedback.value = t('kbWorkspace.msg.pathUploadEmptyFolder');
feedbackType.value = 'error';
return;
}
openDeleteConfirmDialog(
t('kbWorkspace.pathUploadModal.folderConfirmMessage', {
count: files.length,
name: dirHandle.name,
}),
() => {
appendPathUploadFiles(files, (file) => (
(file as File & { webkitRelativePath?: string }).webkitRelativePath || file.name
));
},
{
title: t('kbWorkspace.pathUploadModal.folderConfirmTitle', { count: files.length }),
confirmText: t('kbWorkspace.pathUploadModal.folderConfirmAction'),
confirmTone: 'primary',
},
);
} catch (err) {
// 用户取消选目录不提示
if (err instanceof DOMException && err.name === 'AbortError') return;
feedback.value = t('kbWorkspace.msg.pathUploadPickFailed');
feedbackType.value = 'error';
}
return;
}
pathUploadInputRef.value?.click();
};
/**
* 旧版 input[webkitdirectory] 回退:浏览器会先弹原生确认,再进入本回调。
* 仍用公共确认弹窗二次确认后写入清单。
*/
const handlePathFilesSelected = (event: Event) => {
const input = event.target as HTMLInputElement;
const files = Array.from(input.files || []);
input.value = ''; input.value = '';
const firstFile = files[0];
if (!firstFile) return;
const firstRelative = (firstFile as File & { webkitRelativePath?: string }).webkitRelativePath || firstFile.name;
const folderName = firstRelative.includes('/') ? (firstRelative.split('/')[0] || firstRelative) : firstRelative;
openDeleteConfirmDialog(
t('kbWorkspace.pathUploadModal.folderConfirmMessage', {
count: files.length,
name: folderName,
}),
() => {
appendPathUploadFiles(files);
},
{
title: t('kbWorkspace.pathUploadModal.folderConfirmTitle', { count: files.length }),
confirmText: t('kbWorkspace.pathUploadModal.folderConfirmAction'),
confirmTone: 'primary',
},
);
}; };
const removeSelectedPathFile = (key: string) => { const removeSelectedPathFile = (key: string) => {
+15
View File
@@ -122,12 +122,18 @@
"edit": "Edit Department", "edit": "Edit Department",
"add": "Add New Department", "add": "Add New Department",
"noDepts": "No departments configured.", "noDepts": "No departments configured.",
"noSearchResults": "No matching departments found",
"searchPlaceholder": "Search by name, code, or company…",
"headers": { "headers": {
"name": "Name", "name": "Name",
"code": "Code", "code": "Code",
"company": "Company", "company": "Company",
"actions": "Actions" "actions": "Actions"
}, },
"actions": {
"edit": "Edit",
"delete": "Delete"
},
"fields": { "fields": {
"name": "Name", "name": "Name",
"namePlaceholder": "e.g. IT Department", "namePlaceholder": "e.g. IT Department",
@@ -716,6 +722,7 @@
"allRoles": "All Roles", "allRoles": "All Roles",
"headers": { "headers": {
"user": "User", "user": "User",
"realName": "Real Name",
"dept": "Dept" "dept": "Dept"
}, },
"batchModal": { "batchModal": {
@@ -786,6 +793,14 @@
"noData": "No data available for {table}", "noData": "No data available for {table}",
"noFilterResults": "No matching rows. Adjust your filters.", "noFilterResults": "No matching rows. Adjust your filters.",
"usage": "Usage Analytics", "usage": "Usage Analytics",
"usageRangeLabel": "Time range",
"usageRanges": {
"7d": "Last 7 days",
"30d": "Last 30 days",
"90d": "Last 3 months",
"180d": "Last 6 months",
"365d": "Last 12 months"
},
"byUser": "Requests by User", "byUser": "Requests by User",
"byAgent": "Requests by Agent", "byAgent": "Requests by Agent",
"usageByUserTopHint": "Top {limit} users by chat volume", "usageByUserTopHint": "Top {limit} users by chat volume",
+5
View File
@@ -26,5 +26,10 @@
"itemsUnit": "rows", "itemsUnit": "rows",
"prevPage": "Previous", "prevPage": "Previous",
"nextPage": "Next" "nextPage": "Next"
},
"sort": {
"unsorted": "Click to sort",
"asc": "Ascending, click for descending",
"desc": "Descending, click for ascending"
} }
} }
+6 -1
View File
@@ -277,7 +277,10 @@
"selectedRoots": "Selected roots: {paths}", "selectedRoots": "Selected roots: {paths}",
"noRoots": "None", "noRoots": "None",
"pickFolderFirst": "Select a local folder before confirming upload.", "pickFolderFirst": "Select a local folder before confirming upload.",
"confirmUpload": "Confirm upload" "confirmUpload": "Confirm upload",
"folderConfirmTitle": "Upload {count} files?",
"folderConfirmMessage": "All files under “{name}” will be imported. Continue only if this folder is correct.",
"folderConfirmAction": "Upload"
}, },
"pathUploadHistoryModal": { "pathUploadHistoryModal": {
"title": "Path upload history", "title": "Path upload history",
@@ -365,6 +368,8 @@
"pathUploadBusy": "Upload in progress, please wait", "pathUploadBusy": "Upload in progress, please wait",
"selectGroupFirst": "Please select a group first", "selectGroupFirst": "Please select a group first",
"selectPathFiles": "Please select at least one local folder or file", "selectPathFiles": "Please select at least one local folder or file",
"pathUploadEmptyFolder": "The selected folder has no files to upload",
"pathUploadPickFailed": "Failed to pick a local folder. Retry or use another browser",
"createPathJobFailed": "Failed to create path upload job", "createPathJobFailed": "Failed to create path upload job",
"pathStageFailed": "Path file staging failed", "pathStageFailed": "Path file staging failed",
"pathUploadDone": "Path files uploaded and clean submitted", "pathUploadDone": "Path files uploaded and clean submitted",
+15
View File
@@ -122,12 +122,18 @@
"edit": "แก้ไขแผนก", "edit": "แก้ไขแผนก",
"add": "เพิ่มแผนกใหม่", "add": "เพิ่มแผนกใหม่",
"noDepts": "ยังไม่มีการกำหนดค่าแผนก", "noDepts": "ยังไม่มีการกำหนดค่าแผนก",
"noSearchResults": "ไม่พบแผนกที่ตรงกัน",
"searchPlaceholder": "ค้นหาชื่อ รหัส หรือบริษัท…",
"headers": { "headers": {
"name": "ชื่อ", "name": "ชื่อ",
"code": "รหัส", "code": "รหัส",
"company": "บริษัท", "company": "บริษัท",
"actions": "การกระทำ" "actions": "การกระทำ"
}, },
"actions": {
"edit": "แก้ไข",
"delete": "ลบ"
},
"fields": { "fields": {
"name": "ชื่อ", "name": "ชื่อ",
"namePlaceholder": "เช่น แผนกไอที", "namePlaceholder": "เช่น แผนกไอที",
@@ -721,6 +727,7 @@
"allRoles": "ทุกบทบาท", "allRoles": "ทุกบทบาท",
"headers": { "headers": {
"user": "ผู้ใช้", "user": "ผู้ใช้",
"realName": "ชื่อจริง",
"dept": "แผนก" "dept": "แผนก"
}, },
"batchModal": { "batchModal": {
@@ -791,6 +798,14 @@
"noData": "ไม่มีข้อมูลสำหรับ {table}", "noData": "ไม่มีข้อมูลสำหรับ {table}",
"noFilterResults": "ไม่พบข้อมูลที่ตรงกับเงื่อนไข โปรดปรับตัวกรอง", "noFilterResults": "ไม่พบข้อมูลที่ตรงกับเงื่อนไข โปรดปรับตัวกรอง",
"usage": "การวิเคราะห์การใช้งาน", "usage": "การวิเคราะห์การใช้งาน",
"usageRangeLabel": "ช่วงเวลา",
"usageRanges": {
"7d": "7 วันล่าสุด",
"30d": "30 วันล่าสุด",
"90d": "3 เดือนล่าสุด",
"180d": "6 เดือนล่าสุด",
"365d": "12 เดือนล่าสุด"
},
"byUser": "ตามผู้ใช้", "byUser": "ตามผู้ใช้",
"byAgent": "ตามตัวแทน", "byAgent": "ตามตัวแทน",
"usageByUserTopHint": "แสดงผู้ใช้ {limit} อันดับแรกตามปริมาณการสนทนา", "usageByUserTopHint": "แสดงผู้ใช้ {limit} อันดับแรกตามปริมาณการสนทนา",
+5
View File
@@ -26,5 +26,10 @@
"itemsUnit": "รายการ", "itemsUnit": "รายการ",
"prevPage": "ก่อนหน้า", "prevPage": "ก่อนหน้า",
"nextPage": "ถัดไป" "nextPage": "ถัดไป"
},
"sort": {
"unsorted": "คลิกเพื่อเรียงลำดับ",
"asc": "เรียงจากน้อยไปมาก คลิกเพื่อสลับ",
"desc": "เรียงจากมากไปน้อย คลิกเพื่อสลับ"
} }
} }
+6 -1
View File
@@ -277,7 +277,10 @@
"selectedRoots": "root ที่เลือก: {paths}", "selectedRoots": "root ที่เลือก: {paths}",
"noRoots": "ไม่มี", "noRoots": "ไม่มี",
"pickFolderFirst": "โปรดเลือกโฟลเดอร์ในเครื่องก่อนยืนยันอัปโหลด", "pickFolderFirst": "โปรดเลือกโฟลเดอร์ในเครื่องก่อนยืนยันอัปโหลด",
"confirmUpload": "ยืนยันอัปโหลด" "confirmUpload": "ยืนยันอัปโหลด",
"folderConfirmTitle": "อัปโหลด {count} ไฟล์หรือไม่?",
"folderConfirmMessage": "จะนำเข้าไฟล์ทั้งหมดจาก “{name}” โปรดยืนยันว่าโฟลเดอร์ถูกต้องก่อนดำเนินการต่อ",
"folderConfirmAction": "อัปโหลด"
}, },
"pathUploadHistoryModal": { "pathUploadHistoryModal": {
"title": "ประวัติ batch อัปโหลด path", "title": "ประวัติ batch อัปโหลด path",
@@ -365,6 +368,8 @@
"pathUploadBusy": "กำลังอัปโหลด โปรดรอสักครู่", "pathUploadBusy": "กำลังอัปโหลด โปรดรอสักครู่",
"selectGroupFirst": "โปรดเลือกกลุ่มก่อน", "selectGroupFirst": "โปรดเลือกกลุ่มก่อน",
"selectPathFiles": "โปรดเลือกโฟลเดอร์หรือไฟล์ในเครื่องอย่างน้อยหนึ่งรายการ", "selectPathFiles": "โปรดเลือกโฟลเดอร์หรือไฟล์ในเครื่องอย่างน้อยหนึ่งรายการ",
"pathUploadEmptyFolder": "โฟลเดอร์ที่เลือกไม่มีไฟล์ให้อัปโหลด",
"pathUploadPickFailed": "เลือกโฟลเดอร์ในเครื่องไม่สำเร็จ โปรดลองใหม่หรือใช้เบราว์เซอร์อื่น",
"createPathJobFailed": "สร้างงานอัปโหลด path ล้มเหลว", "createPathJobFailed": "สร้างงานอัปโหลด path ล้มเหลว",
"pathStageFailed": "จัดเก็บไฟล์ path ชั่วคราวล้มเหลว", "pathStageFailed": "จัดเก็บไฟล์ path ชั่วคราวล้มเหลว",
"pathUploadDone": "อัปโหลดไฟล์ path และส่งทำความสะอาดแล้ว", "pathUploadDone": "อัปโหลดไฟล์ path และส่งทำความสะอาดแล้ว",
+15
View File
@@ -123,12 +123,18 @@
"edit": "编辑部门", "edit": "编辑部门",
"add": "添加部门", "add": "添加部门",
"noDepts": "暂无部门配置", "noDepts": "暂无部门配置",
"noSearchResults": "未找到匹配的部门",
"searchPlaceholder": "搜索名称、编码或公司…",
"headers": { "headers": {
"name": "名称", "name": "名称",
"code": "编码", "code": "编码",
"company": "公司", "company": "公司",
"actions": "操作" "actions": "操作"
}, },
"actions": {
"edit": "编辑",
"delete": "删除"
},
"fields": { "fields": {
"name": "名称", "name": "名称",
"namePlaceholder": "例如:信息技术部", "namePlaceholder": "例如:信息技术部",
@@ -717,6 +723,7 @@
"allRoles": "所有角色", "allRoles": "所有角色",
"headers": { "headers": {
"user": "用户", "user": "用户",
"realName": "真实姓名",
"dept": "部门" "dept": "部门"
}, },
"batchModal": { "batchModal": {
@@ -787,6 +794,14 @@
"noData": "暂无数据: {table}", "noData": "暂无数据: {table}",
"noFilterResults": "没有匹配的数据,请调整筛选条件", "noFilterResults": "没有匹配的数据,请调整筛选条件",
"usage": "使用分析", "usage": "使用分析",
"usageRangeLabel": "统计范围",
"usageRanges": {
"7d": "近一周",
"30d": "近一月",
"90d": "近三月",
"180d": "近半年",
"365d": "近一年"
},
"byUser": "按用户统计", "byUser": "按用户统计",
"byAgent": "按应用统计", "byAgent": "按应用统计",
"usageByUserTopHint": "仅显示对话量前 {limit} 名用户", "usageByUserTopHint": "仅显示对话量前 {limit} 名用户",
+5
View File
@@ -26,5 +26,10 @@
"itemsUnit": "条", "itemsUnit": "条",
"prevPage": "上一页", "prevPage": "上一页",
"nextPage": "下一页" "nextPage": "下一页"
},
"sort": {
"unsorted": "点击排序",
"asc": "升序,点击切换为降序",
"desc": "降序,点击切换为升序"
} }
} }
+6 -1
View File
@@ -277,7 +277,10 @@
"selectedRoots": "已选根路径:{paths}", "selectedRoots": "已选根路径:{paths}",
"noRoots": "暂无", "noRoots": "暂无",
"pickFolderFirst": "请选择本地目录后再确认上传。", "pickFolderFirst": "请选择本地目录后再确认上传。",
"confirmUpload": "确认上传" "confirmUpload": "确认上传",
"folderConfirmTitle": "是否上传 {count} 个文件?",
"folderConfirmMessage": "将从「{name}」导入所选目录下的全部文件。请确认目录无误后再继续。",
"folderConfirmAction": "上传"
}, },
"pathUploadHistoryModal": { "pathUploadHistoryModal": {
"title": "上传路径历史批次", "title": "上传路径历史批次",
@@ -365,6 +368,8 @@
"pathUploadBusy": "有文件正在上传请稍等再试~", "pathUploadBusy": "有文件正在上传请稍等再试~",
"selectGroupFirst": "请先选择知识库分组", "selectGroupFirst": "请先选择知识库分组",
"selectPathFiles": "请先选择至少一个本地目录或文件", "selectPathFiles": "请先选择至少一个本地目录或文件",
"pathUploadEmptyFolder": "所选目录下没有可上传的文件",
"pathUploadPickFailed": "选择本地目录失败,请重试或换用其他浏览器",
"createPathJobFailed": "创建上传路径任务失败", "createPathJobFailed": "创建上传路径任务失败",
"pathStageFailed": "路径文件暂存失败", "pathStageFailed": "路径文件暂存失败",
"pathUploadDone": "路径文件已逐个上传并提交清洗", "pathUploadDone": "路径文件已逐个上传并提交清洗",
+15
View File
@@ -122,12 +122,18 @@
"edit": "編輯部門", "edit": "編輯部門",
"add": "添加部門", "add": "添加部門",
"noDepts": "暫無部門配置", "noDepts": "暫無部門配置",
"noSearchResults": "未找到匹配的部門",
"searchPlaceholder": "搜尋名稱、編碼或公司…",
"headers": { "headers": {
"name": "名稱", "name": "名稱",
"code": "編碼", "code": "編碼",
"company": "公司", "company": "公司",
"actions": "操作" "actions": "操作"
}, },
"actions": {
"edit": "編輯",
"delete": "刪除"
},
"fields": { "fields": {
"name": "名稱", "name": "名稱",
"namePlaceholder": "例如:資訊技術部", "namePlaceholder": "例如:資訊技術部",
@@ -721,6 +727,7 @@
"allRoles": "所有角色", "allRoles": "所有角色",
"headers": { "headers": {
"user": "用戶", "user": "用戶",
"realName": "真實姓名",
"dept": "部門" "dept": "部門"
}, },
"batchModal": { "batchModal": {
@@ -791,6 +798,14 @@
"noData": "暫無數據: {table}", "noData": "暫無數據: {table}",
"noFilterResults": "沒有匹配的數據,請調整篩選條件", "noFilterResults": "沒有匹配的數據,請調整篩選條件",
"usage": "使用分析", "usage": "使用分析",
"usageRangeLabel": "統計範圍",
"usageRanges": {
"7d": "近一週",
"30d": "近一月",
"90d": "近三月",
"180d": "近半年",
"365d": "近一年"
},
"byUser": "按用戶統計", "byUser": "按用戶統計",
"byAgent": "按應用統計", "byAgent": "按應用統計",
"usageByUserTopHint": "僅顯示對話量前 {limit} 名用戶", "usageByUserTopHint": "僅顯示對話量前 {limit} 名用戶",
+5
View File
@@ -26,5 +26,10 @@
"itemsUnit": "條", "itemsUnit": "條",
"prevPage": "上一頁", "prevPage": "上一頁",
"nextPage": "下一頁" "nextPage": "下一頁"
},
"sort": {
"unsorted": "點擊排序",
"asc": "升序,點擊切換為降序",
"desc": "降序,點擊切換為升序"
} }
} }
+6 -1
View File
@@ -277,7 +277,10 @@
"selectedRoots": "已選根路徑:{paths}", "selectedRoots": "已選根路徑:{paths}",
"noRoots": "暫無", "noRoots": "暫無",
"pickFolderFirst": "請選擇本地目錄後再確認上傳。", "pickFolderFirst": "請選擇本地目錄後再確認上傳。",
"confirmUpload": "確認上傳" "confirmUpload": "確認上傳",
"folderConfirmTitle": "是否上傳 {count} 個檔案?",
"folderConfirmMessage": "將從「{name}」匯入所選目錄下的全部檔案。請確認目錄無誤後再繼續。",
"folderConfirmAction": "上傳"
}, },
"pathUploadHistoryModal": { "pathUploadHistoryModal": {
"title": "上傳路徑歷史批次", "title": "上傳路徑歷史批次",
@@ -365,6 +368,8 @@
"pathUploadBusy": "有文件正在上傳請稍等再試~", "pathUploadBusy": "有文件正在上傳請稍等再試~",
"selectGroupFirst": "請先選擇知識庫分組", "selectGroupFirst": "請先選擇知識庫分組",
"selectPathFiles": "請先選擇至少一個本地目錄或文件", "selectPathFiles": "請先選擇至少一個本地目錄或文件",
"pathUploadEmptyFolder": "所選目錄下沒有可上傳的檔案",
"pathUploadPickFailed": "選擇本地目錄失敗,請重試或改用其他瀏覽器",
"createPathJobFailed": "創建上傳路徑任務失敗", "createPathJobFailed": "創建上傳路徑任務失敗",
"pathStageFailed": "路徑文件暫存失敗", "pathStageFailed": "路徑文件暫存失敗",
"pathUploadDone": "路徑文件已逐個上傳並提交清洗", "pathUploadDone": "路徑文件已逐個上傳並提交清洗",
@@ -1,7 +1,9 @@
<script setup lang="ts"> <script setup lang="ts">
/** /**
* shared/components/DeleteConfirmDialog.vue * shared/components/DeleteConfirmDialog.vue
* 通用确认弹窗(默认删除场景,可通过 title / confirmTone 用于其它确认)。 * 用途:通用确认弹窗(默认删除;可通过 title / confirmTone / confirmText 用于上传路径等确认)。
* 依赖:vue-i18n、dialog-overlay / dialog-panel 设计系统样式。
* 逻辑:KbWorkspaceOverlays、ChatViewOverlays、各管理端页面以 v-model 控制显隐。
*/ */
import { computed, onBeforeUnmount, watch } from 'vue'; import { computed, onBeforeUnmount, watch } from 'vue';
@@ -0,0 +1,62 @@
/**
* shared/components/SortableTableHeader.vue
* 用途:可点击的表格排序表头(文案 + 升/降/未排序图标)。
* 依赖:lucide 图标、common.sort i18n、table-sort 类型。
* 逻辑:管理端表格 th 内使用;点击 emit sort,由 useTableSort.toggleSort 处理。
*/
<script setup lang="ts" generic="K extends string">
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { ArrowDown, ArrowUp, ArrowUpDown } from 'lucide-vue-next';
import type { SortDir } from '@/shared/utils/table-sort';
const props = withDefaults(
defineProps<{
/** 本列表头对应的列键 */
columnKey: K;
/** 表头展示文案 */
label: string;
/** 当前激活的排序列 */
activeKey?: K;
/** 当前排序方向 */
direction?: SortDir;
/** 对齐方式 */
align?: 'left' | 'right';
}>(),
{
direction: 'asc',
align: 'left',
},
);
const emit = defineEmits<{
sort: [key: K];
}>();
const { t } = useI18n();
const isActive = computed(() => props.activeKey === props.columnKey);
/**
* 无障碍 title:标明未排序 / 升序 / 降序。
*/
const title = computed(() => {
if (!isActive.value) return t('common.sort.unsorted');
return props.direction === 'asc' ? t('common.sort.asc') : t('common.sort.desc');
});
</script>
<template>
<button
type="button"
class="inline-flex items-center gap-1.5 hover:text-primary transition-colors"
:class="align === 'right' ? 'ml-auto' : ''"
:title="title"
@click="emit('sort', columnKey)"
>
<span>{{ label }}</span>
<ArrowUp v-if="isActive && direction === 'asc'" class="w-3.5 h-3.5 text-brand-600" />
<ArrowDown v-else-if="isActive && direction === 'desc'" class="w-3.5 h-3.5 text-brand-600" />
<ArrowUpDown v-else class="w-3.5 h-3.5 opacity-40" />
</button>
</template>
@@ -1,10 +1,8 @@
/** /**
* shared/composables/useReportLayoutStorage.ts * shared/composables/useReportLayoutStorage.ts
* 报表页面布局偏好 localStorage 持久化。 * 用途:报表页面布局偏好 localStorage 持久化(按用户 + 表名隔离)。
*/ * 依赖:localStorage / sessionStorage 中的 hxops_user。
/** * 逻辑:ReportsPage / useReportsAdmin 读写列宽、显隐与排序偏好;v3 起聊天日志默认列宽收窄。
* useReportLayoutStorage.ts
* 用途:为报表页面提供统一的布局偏好持久化能力(按用户 + 表名隔离)
*/ */
const getCurrentAuthUser = () => { const getCurrentAuthUser = () => {
@@ -24,10 +22,20 @@ const getCurrentIdentity = () => {
return user?.id ? `id_${user.id}` : `u_${user?.username || 'guest'}`; return user?.id ? `id_${user.id}` : `u_${user?.username || 'guest'}`;
}; };
/**
* 生成报表布局偏好的 storage key。
* @param table - 报表表名(如 chat_logs)
*/
const getReportLayoutStorageKey = (table: string) => { const getReportLayoutStorageKey = (table: string) => {
return `hxops_report_layout_v2_${getCurrentIdentity()}_${table}`; // v3:聊天日志默认列宽收窄(应用名/用户/姓名/Token),旧 v2 偏好不再沿用
return `hxops_report_layout_v3_${getCurrentIdentity()}_${table}`;
}; };
/**
* 读取指定报表表的布局偏好。
* @param table - 报表表名
* @returns 解析后的偏好,失败或不存在时返回 null
*/
export const loadReportLayoutPref = <T = any>(table: string): T | null => { export const loadReportLayoutPref = <T = any>(table: string): T | null => {
try { try {
const raw = localStorage.getItem(getReportLayoutStorageKey(table)); const raw = localStorage.getItem(getReportLayoutStorageKey(table));
@@ -38,6 +46,11 @@ export const loadReportLayoutPref = <T = any>(table: string): T | null => {
} }
}; };
/**
* 写入指定报表表的布局偏好。
* @param table - 报表表名
* @param payload - 可序列化的布局对象
*/
export const saveReportLayoutPref = (table: string, payload: unknown) => { export const saveReportLayoutPref = (table: string, payload: unknown) => {
try { try {
localStorage.setItem(getReportLayoutStorageKey(table), JSON.stringify(payload)); localStorage.setItem(getReportLayoutStorageKey(table), JSON.stringify(payload));
@@ -45,4 +58,3 @@ export const saveReportLayoutPref = (table: string, payload: unknown) => {
// Ignore storage write failure to avoid blocking core report flow. // Ignore storage write failure to avoid blocking core report flow.
} }
}; };
@@ -0,0 +1,66 @@
/**
* shared/composables/useTableSort.ts
* 用途:表格列排序状态(当前列、方向)与切换/排序辅助。
* 依赖:vue ref、table-sort 纯函数。
* 逻辑:业务 composable(如 useDepartmentsAdmin)注入本 hook,页面用 SortableTableHeader 展示。
*/
import { ref } from 'vue';
import {
nextSortState,
sortByKey,
type SortComparable,
type SortDir,
} from '@/shared/utils/table-sort';
export interface UseTableSortOptions<K extends string> {
/** 初始排序列 */
initialKey?: K;
/** 初始方向,默认 asc */
initialDir?: SortDir;
}
/**
* 管理表格排序状态,并提供按当前状态排序列表的方法。
* @param options.initialKey - 默认排序列
* @param options.initialDir - 默认方向
*/
export function useTableSort<K extends string>(options: UseTableSortOptions<K> = {}) {
const sortKey = ref(options.initialKey as K | undefined);
const sortDir = ref<SortDir>(options.initialDir ?? 'asc');
/**
* 切换表头排序:同列升/降切换,换列从升序开始。
* @param key - 点击的列键
*/
const toggleSort = (key: K): void => {
const next = nextSortState(sortKey.value, sortDir.value, key);
sortKey.value = next.sortKey;
sortDir.value = next.sortDir;
};
/**
* 按当前 sortKey / sortDir 对列表排序。
* @param items - 源列表
* @param getValue - 从行取比较值
* @param tieBreaker - 可选稳定次序
* @returns 新排序数组
*/
const sortItems = <T>(
items: readonly T[],
getValue: (item: T, key: K) => SortComparable,
tieBreaker?: (a: T, b: T) => number,
): T[] =>
sortByKey(items, {
sortKey: sortKey.value,
sortDir: sortDir.value,
getValue,
tieBreaker,
});
return {
sortKey,
sortDir,
toggleSort,
sortItems,
};
}
+2
View File
@@ -8,6 +8,8 @@ export * from './composables/useIsMobile';
export * from './composables/useGlobalMessageDialog'; export * from './composables/useGlobalMessageDialog';
export * from './composables/useReportLayoutStorage'; export * from './composables/useReportLayoutStorage';
export * from './composables/useAudioTranscription'; export * from './composables/useAudioTranscription';
export * from './composables/useTableSort';
export * from './utils/table-sort';
export * from './api/client'; export * from './api/client';
export * from './constants/routes'; export * from './constants/routes';
export type * from './types/schedule.types'; export type * from './types/schedule.types';
+1 -1
View File
@@ -395,7 +395,7 @@
} }
.admin-report-filter-input { .admin-report-filter-input {
@apply w-full px-2 py-1 text-xs border rounded outline-none font-normal normal-case; @apply w-full max-w-full min-w-0 box-border px-1.5 py-1 text-xs border rounded outline-none font-normal normal-case;
border-color: var(--border-default); border-color: var(--border-default);
background-color: var(--bg-surface); background-color: var(--bg-surface);
color: var(--text-primary); color: var(--text-primary);
@@ -0,0 +1,52 @@
/**
* shared/utils/table-sort.test.ts
* 用途:保护表格列排序纯函数的比较与切换语义。
* 依赖:Vitest、table-sort。
* 逻辑:覆盖空值、数字自然序、同列切换方向、换列重置升序。
*/
import { describe, expect, it } from 'vitest';
import {
compareSortValues,
nextSortState,
normalizeSortValue,
sortByKey,
} from './table-sort';
describe('table-sort utils', () => {
it('normalizes blank strings to null', () => {
expect(normalizeSortValue(' ')).toBeNull();
expect(normalizeSortValue('IT')).toBe('IT');
expect(normalizeSortValue(12)).toBe(12);
});
it('compares numeric-looking codes naturally', () => {
expect(compareSortValues('2', '10')).toBeLessThan(0);
expect(compareSortValues(null, 'a')).toBe(1);
});
it('toggles direction on same key and resets on new key', () => {
expect(nextSortState('name', 'asc', 'name')).toEqual({
sortKey: 'name',
sortDir: 'desc',
});
expect(nextSortState('name', 'desc', 'code')).toEqual({
sortKey: 'code',
sortDir: 'asc',
});
});
it('sorts rows by key with id tie-breaker', () => {
const rows = [
{ id: 2, name: 'B' },
{ id: 1, name: 'A' },
{ id: 3, name: 'A' },
];
const sorted = sortByKey(rows, {
sortKey: 'name',
sortDir: 'asc',
getValue: (row, key) => row[key],
tieBreaker: (a, b) => a.id - b.id,
});
expect(sorted.map((r) => r.id)).toEqual([1, 3, 2]);
});
});
+102
View File
@@ -0,0 +1,102 @@
/**
* shared/utils/table-sort.ts
* 用途:管理端表格列排序的纯函数(比较、切换方向、按列排序)。
* 依赖:无。
* 逻辑:useTableSort / SortableTableHeader 复用;业务页传入取值函数即可。
*/
export type SortDir = 'asc' | 'desc';
/** 可参与比较的原始值(空值统一排后) */
export type SortComparable = string | number | null | undefined;
/**
* 规范化比较值:字符串 trim,空串/null/undefined 视为空。
* @param value - 原始字段值
* @returns 规范化后的 string | number,空则为 null
*/
export function normalizeSortValue(value: SortComparable): string | number | null {
if (value == null) return null;
if (typeof value === 'number') {
return Number.isFinite(value) ? value : null;
}
const trimmed = String(value).trim();
return trimmed ? trimmed : null;
}
/**
* 比较两个规范化后的排序值。
* 核心逻辑:空值排后;数字直接相减;字符串用 localeCompare(numeric)。
* @param a - 左值
* @param b - 右值
* @returns 负/零/正,与 Array.sort 约定一致
*/
export function compareSortValues(
a: string | number | null,
b: string | number | null,
): number {
if (a == null && b == null) return 0;
if (a == null) return 1;
if (b == null) return -1;
if (typeof a === 'number' && typeof b === 'number') return a - b;
return String(a).localeCompare(String(b), undefined, {
numeric: true,
sensitivity: 'base',
});
}
/**
* 切换排序状态:同列在升/降序间切换,换列则从升序开始。
* @param currentKey - 当前排序列
* @param currentDir - 当前方向
* @param nextKey - 点击的列
* @returns 新的 sortKey / sortDir
*/
export function nextSortState<K extends string>(
currentKey: K | undefined,
currentDir: SortDir,
nextKey: K,
): { sortKey: K; sortDir: SortDir } {
if (currentKey === nextKey) {
return {
sortKey: nextKey,
sortDir: currentDir === 'asc' ? 'desc' : 'asc',
};
}
return { sortKey: nextKey, sortDir: 'asc' };
}
export interface SortByKeyOptions<T, K extends string> {
/** 当前排序列;未指定时返回浅拷贝原列表 */
sortKey?: K;
sortDir?: SortDir;
/** 从行中取出比较值 */
getValue: (item: T, key: K) => SortComparable;
/** 主值相等时的稳定次序(如按 id) */
tieBreaker?: (a: T, b: T) => number;
}
/**
* 按指定列对列表排序(不修改原数组)。
* @param items - 源列表
* @param options - 排序列、方向、取值与 tie-break
* @returns 新排序数组
*/
export function sortByKey<T, K extends string>(
items: readonly T[],
options: SortByKeyOptions<T, K>,
): T[] {
const { sortKey, sortDir = 'asc', getValue, tieBreaker } = options;
const list = [...items];
if (!sortKey) return list;
const dir = sortDir === 'asc' ? 1 : -1;
list.sort((a, b) => {
const av = normalizeSortValue(getValue(a, sortKey));
const bv = normalizeSortValue(getValue(b, sortKey));
const cmp = compareSortValues(av, bv);
if (cmp !== 0) return cmp * dir;
return tieBreaker ? tieBreaker(a, b) : 0;
});
return list;
}
+375
View File
@@ -0,0 +1,375 @@
#!/usr/bin/env python3
"""
scripts/split_large_pdfs_for_kb.py
用途:将超大扫描 PDF(如机械设计手册整卷)按固定页数切成适合知识库上传/清洗的小文件。
依赖:pypdf(`pip install pypdf`)。
逻辑:运维/入库前离线执行;产出小 PDF + manifest.csv,再由知识库路径上传导入 HXOPS。
"""
from __future__ import annotations
import argparse
import csv
import re
import sys
import time
from dataclasses import dataclass
from pathlib import Path
@dataclass(frozen=True)
class SplitPlan:
"""单卷 PDF 的切分计划。"""
source: Path
total_pages: int
chunk_count: int
pages_per_chunk: int
def _slugify_stem(name: str) -> str:
"""
将文件名主干整理为适合输出的安全片段(保留中文与常见字符)。
核心逻辑:去掉扩展名无关字符中的路径分隔与空白折叠,避免输出路径非法。
Args:
name: 原始文件名(可含扩展名)。
Returns:
清理后的 stem 字符串。
"""
stem = Path(name).stem.strip()
stem = re.sub(r'[<>:"/\\|?*\x00-\x1f]', "_", stem)
stem = re.sub(r"\s+", "_", stem)
return stem or "document"
def _iter_pdfs(input_dir: Path, recursive: bool) -> list[Path]:
"""
收集待拆分的 PDF 路径列表。
Args:
input_dir: 输入目录。
recursive: 是否递归子目录。
Returns:
按文件名排序的 PDF 路径列表。
"""
pattern = "**/*.pdf" if recursive else "*.pdf"
files = [p for p in input_dir.glob(pattern) if p.is_file()]
return sorted(files, key=lambda p: p.name.lower())
def plan_split(source: Path, pages_per_chunk: int) -> SplitPlan:
"""
读取 PDF 页数并计算切分份数(不写文件)。
核心逻辑:用 pypdf.PdfReader 取页数,按 pages_per_chunk 向上取整。
Args:
source: 源 PDF 路径。
pages_per_chunk: 每份页数,须 >= 1。
Returns:
SplitPlan。
Raises:
ValueError: 页数无效或无法打开 PDF。
"""
from pypdf import PdfReader
reader = PdfReader(str(source), strict=False)
total = len(reader.pages)
if total <= 0:
raise ValueError(f"PDF 页数为 0: {source}")
chunk_count = (total + pages_per_chunk - 1) // pages_per_chunk
return SplitPlan(
source=source,
total_pages=total,
chunk_count=chunk_count,
pages_per_chunk=pages_per_chunk,
)
def split_one_pdf(
source: Path,
output_dir: Path,
pages_per_chunk: int,
*,
dry_run: bool = False,
overwrite: bool = False,
) -> list[dict[str, object]]:
"""
将单个 PDF 按固定页数切分为多个小 PDF,并返回 manifest 行。
核心逻辑:一次打开源文件,按页区间用 PdfWriter 写出;文件名含起止页码便于溯源。
Args:
source: 源 PDF。
output_dir: 输出目录(不存在则创建)。
pages_per_chunk: 每份页数。
dry_run: 为 True 时只规划不写文件。
overwrite: 为 False 时若目标已存在则跳过该份。
Returns:
manifest 行字典列表(source/output/pages/size 等)。
"""
from pypdf import PdfReader, PdfWriter
plan = plan_split(source, pages_per_chunk)
stem = _slugify_stem(source.name)
output_dir.mkdir(parents=True, exist_ok=True)
rows: list[dict[str, object]] = []
if dry_run:
for idx in range(plan.chunk_count):
start = idx * pages_per_chunk
end = min(start + pages_per_chunk, plan.total_pages)
out_name = f"{stem}_p{start + 1:04d}-{end:04d}.pdf"
rows.append(
{
"source": str(source),
"output": str(output_dir / out_name),
"part_index": idx + 1,
"part_count": plan.chunk_count,
"page_start": start + 1,
"page_end": end,
"page_count": end - start,
"size_bytes": "",
"status": "planned",
}
)
return rows
# [STEP 1] 打开源 PDF(扫描件可能很大,保持单次打开复用)
print(f"[open] {source.name} pages={plan.total_pages} parts={plan.chunk_count}")
reader = PdfReader(str(source), strict=False)
t0 = time.time()
for idx in range(plan.chunk_count):
start = idx * pages_per_chunk
end = min(start + pages_per_chunk, plan.total_pages)
out_name = f"{stem}_p{start + 1:04d}-{end:04d}.pdf"
out_path = output_dir / out_name
if out_path.exists() and not overwrite:
size = out_path.stat().st_size
print(f" [skip] {out_name} (exists, {size / (1024 * 1024):.1f} MB)")
rows.append(
{
"source": str(source),
"output": str(out_path),
"part_index": idx + 1,
"part_count": plan.chunk_count,
"page_start": start + 1,
"page_end": end,
"page_count": end - start,
"size_bytes": size,
"status": "skipped_exists",
}
)
continue
# [STEP 2] 按页区间写出小 PDF
writer = PdfWriter()
for page_i in range(start, end):
writer.add_page(reader.pages[page_i])
with out_path.open("wb") as fh:
writer.write(fh)
size = out_path.stat().st_size
size_mb = size / (1024 * 1024)
warn = " !! >50MB" if size_mb > 50 else ""
print(
f" [{idx + 1}/{plan.chunk_count}] {out_name} "
f"pages={start + 1}-{end} {size_mb:.1f} MB{warn}"
)
rows.append(
{
"source": str(source),
"output": str(out_path),
"part_index": idx + 1,
"part_count": plan.chunk_count,
"page_start": start + 1,
"page_end": end,
"page_count": end - start,
"size_bytes": size,
"status": "written",
}
)
print(f"[done] {source.name} elapsed={time.time() - t0:.1f}s")
return rows
def write_manifest(rows: list[dict[str, object]], manifest_path: Path) -> None:
"""
将切分结果写入 CSV,便于核对与后续批量上传。
Args:
rows: manifest 行。
manifest_path: 输出 CSV 路径。
"""
if not rows:
return
fieldnames = [
"source",
"output",
"part_index",
"part_count",
"page_start",
"page_end",
"page_count",
"size_bytes",
"status",
]
manifest_path.parent.mkdir(parents=True, exist_ok=True)
with manifest_path.open("w", encoding="utf-8-sig", newline="") as fh:
writer = csv.DictWriter(fh, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(rows)
def build_arg_parser() -> argparse.ArgumentParser:
"""
构建命令行参数解析器。
Returns:
ArgumentParser 实例。
"""
parser = argparse.ArgumentParser(
description="按固定页数拆分超大 PDF,便于知识库上传与 OCR 清洗。"
)
parser.add_argument(
"--input",
required=True,
help="源 PDF 文件或包含 PDF 的目录",
)
parser.add_argument(
"--output",
required=True,
help="拆分结果输出目录",
)
parser.add_argument(
"--pages",
type=int,
default=40,
help="每份页数(扫描件建议 20–40;默认 40)",
)
parser.add_argument(
"--recursive",
action="store_true",
help="输入为目录时递归查找 PDF",
)
parser.add_argument(
"--dry-run",
action="store_true",
help="只打印/写出计划,不真正切分",
)
parser.add_argument(
"--overwrite",
action="store_true",
help="覆盖已存在的输出文件",
)
parser.add_argument(
"--manifest",
default="",
help="manifest CSV 路径(默认写到输出目录/manifest.csv)",
)
return parser
def main(argv: list[str] | None = None) -> int:
"""
CLI 入口:解析参数、切分 PDF、写出 manifest。
Args:
argv: 可选命令行参数列表;默认使用 sys.argv。
Returns:
进程退出码:0 成功,非 0 失败。
"""
args = build_arg_parser().parse_args(argv)
if args.pages < 1:
print("ERROR: --pages 必须 >= 1", file=sys.stderr)
return 2
input_path = Path(args.input)
output_dir = Path(args.output)
if not input_path.exists():
print(f"ERROR: 输入不存在: {input_path}", file=sys.stderr)
return 2
if input_path.is_file():
sources = [input_path]
else:
sources = _iter_pdfs(input_path, recursive=args.recursive)
if not sources:
print(f"ERROR: 目录下未找到 PDF: {input_path}", file=sys.stderr)
return 2
print(
f"sources={len(sources)} pages_per_chunk={args.pages} "
f"dry_run={args.dry_run} output={output_dir}"
)
all_rows: list[dict[str, object]] = []
failed = 0
for source in sources:
try:
# 每卷单独子目录,避免 6 卷文件混在一起难管理
vol_out = output_dir / _slugify_stem(source.name)
rows = split_one_pdf(
source,
vol_out,
args.pages,
dry_run=args.dry_run,
overwrite=args.overwrite,
)
all_rows.extend(rows)
if args.dry_run and rows:
plan_pages = int(rows[0]["page_end"]) # type: ignore[arg-type]
# dry-run 时用 plan_split 再打一行摘要
plan = plan_split(source, args.pages)
size_mb = source.stat().st_size / (1024 * 1024)
print(
f"[plan] {source.name} {size_mb:.1f} MB "
f"pages={plan.total_pages} -> {plan.chunk_count} parts "
f"(~{args.pages} pages each) first_end_check={plan_pages}"
)
except Exception as exc: # noqa: BLE001 - CLI 汇总错误后继续下一卷
failed += 1
print(f"[FAIL] {source}: {exc}", file=sys.stderr)
manifest_path = (
Path(args.manifest) if args.manifest else output_dir / "manifest.csv"
)
write_manifest(all_rows, manifest_path)
written = sum(1 for r in all_rows if r["status"] in {"written", "planned"})
skipped = sum(1 for r in all_rows if r["status"] == "skipped_exists")
print(
f"\nsummary: parts={len(all_rows)} written_or_planned={written} "
f"skipped={skipped} failed_sources={failed}"
)
print(f"manifest: {manifest_path}")
if not args.dry_run and all_rows:
oversized = [
r
for r in all_rows
if isinstance(r.get("size_bytes"), int) and int(r["size_bytes"]) > 50 * 1024 * 1024
]
if oversized:
print(
f"WARNING: {len(oversized)} 个分片 > 50MB,建议减小 --pages 后重跑 "
f"(知识库 Nginx 上限约 100MB,OCR 也更易超时)"
)
return 1 if failed else 0
if __name__ == "__main__":
raise SystemExit(main())