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

+9 -2
View File
@@ -19,7 +19,7 @@ def _query_params() -> dict[str, str]:
@admin_bp.route('/reports/usage', methods=['GET'])
@require_admin
def usage_report():
"""聊天使用分析报表。"""
"""聊天使用分析报表(支持时间范围 range=7d|30d|90d|180d|365d)。"""
try:
user_page = int(request.args.get('user_page', 1))
except (TypeError, ValueError):
@@ -28,7 +28,14 @@ def usage_report():
user_page_size = int(request.args.get('user_page_size', 10))
except (TypeError, ValueError):
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'])
+46 -4
View File
@@ -8,7 +8,7 @@ backend/app/services/admin/report_service.py
from __future__ import annotations
import math
from datetime import datetime
from datetime import datetime, timedelta
from typing import Any
from sqlalchemy import desc, func
@@ -18,13 +18,53 @@ from app.models import Agent, ChatLog, Feedback, GeneralFeedback, User
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:
"""聊天使用分析报表。"""
total = db.session.query(ChatLog).count()
def resolve_usage_range_start(range_key: str | None) -> tuple[str, datetime]:
"""
解析使用分析时间范围,返回规范化 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 = (
db.session.query(Agent.name, func.count(ChatLog.id))
.join(ChatLog)
.filter(base_filter)
.group_by(Agent.name)
.order_by(desc(func.count(ChatLog.id)), Agent.name)
.all()
@@ -34,6 +74,7 @@ def build_usage_report(*, user_page: int, user_page_size: int) -> dict:
by_user_top = (
db.session.query(User.username, func.count(ChatLog.id))
.join(ChatLog)
.filter(base_filter)
.group_by(User.username)
.order_by(desc(func.count(ChatLog.id)), User.username)
.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]
return {
'total': total,
'range': normalized_range,
'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],
'user_total': user_total,
+31 -2
View File
@@ -104,10 +104,39 @@ def apply_users_filters(query, query_params: dict[str, str]):
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:
query = apply_users_filters(db.session.query(User), query_params)
order_by = resolve_users_order_by(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]
try:
@@ -128,7 +157,7 @@ def list_users(query_params: dict[str, str]) -> list[dict] | dict:
users = (
query.options(joinedload(User.agents))
.order_by(User.id.asc())
.order_by(*order_by)
.offset((page - 1) * page_size)
.limit(page_size)
.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
import json
@@ -30,7 +38,7 @@ from edkb_system.skills import (
quality_gate,
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
@@ -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:
"""
判断当前文档是否需要跑 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:
return False
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
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
# 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
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 pipeline_requests_ocr or has_image_blocks
@@ -592,6 +619,13 @@ def _run_one(
if blocks:
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)
if should_ocr:
_announce("ocr")
@@ -614,8 +648,13 @@ def _run_one(
for b in blocks
if b.type in {"heading", "paragraph"}
)
# [STEP] policy_text/flow 默认丢图;手册类必须保留 image+ocr_text 供问答
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:
suppress_images = True
elif (
@@ -627,6 +666,8 @@ def _run_one(
if suppress_images:
blocks = [b for b in blocks if b.type not in {"image", "ocr_text"}]
trace_steps.append("edkb-image-suppress(no_figure_anchor)")
elif figure_rich_handbook:
trace_steps.append("edkb-image-keep(figure_rich_handbook)")
flow_info = {}
if "edkb-flow-reconstruct" in profile.recommended_pipeline:
@@ -642,7 +683,9 @@ def _run_one(
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)
elif tables is not None:
_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
import base64
@@ -907,13 +915,28 @@ def _compact_remarks_to_single_line(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()
ocr_lines = [ln.strip() for ln in lines if ln.strip().startswith("图中文字:")]
if not ocr_lines:
return text
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()))
if img_count <= 0:
return text
@@ -927,6 +950,10 @@ def _attach_ocr_lines_to_images(text: str) -> str:
if img_pat.match(ln.strip()):
out.append(ocr_lines[o_idx])
o_idx += 1
# 多余 OCR 行仍保留,避免手册图注被静默丢弃
while o_idx < len(ocr_lines):
out.append(ocr_lines[o_idx])
o_idx += 1
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
import hashlib
@@ -9,6 +17,45 @@ from typing import Any
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:
return hashlib.sha256(text.encode("utf-8")).hexdigest()
@@ -162,7 +209,23 @@ def _page_image_structured_lines(payload: str) -> list[str]:
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:
token = re.sub(r"\s+", "", text or "")
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:
ocr_text = ocr_by_image.get(b.id)
# [STEP] 手册类保留页图 OCR;普通 PDF 仍避免与正文重复的整页图噪声
suppress_pdf_page_image = (
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 "")
not keep_figure_ocr
and (
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:
lines.append(f"![page-image-{b.page}]")
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})")
ocr_text = ocr_by_image.get(b.id)
if ocr_text:
suppress_pptx_ocr = bool(
b.meta and b.meta.get("page_image_source") == "pptx"
) and (
page_body_chars.get(b.page, 0) >= 15
or page_text_chars.get(b.page, 0) >= 40
suppress_pptx_ocr = (
not keep_figure_ocr
and bool(b.meta and b.meta.get("page_image_source") == "pptx")
and (
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"):
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}")
else:
lines.append("![image]")
ocr_text = ocr_by_image.get(b.id)
if ocr_text and keep_figure_ocr:
lines.append(f"图中文字:{ocr_text}")
else:
lines.append(txt)
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
import base64
@@ -7,6 +15,7 @@ import re
import xml.etree.ElementTree as ET
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_JPEG_QUALITY = 82
@@ -15,6 +24,9 @@ _DEFAULT_PAGE_TEXT_LIMIT = 120
_MIN_SCAN_IMAGE_BYTES = 4 * 1024
_MIN_DEFAULT_IMAGE_BYTES = 16 * 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_SKIP_TAGS = {
"config",
@@ -44,11 +56,33 @@ def _should_keep_embedded_image(
page_text_chars: int,
scan_likely: bool,
text_heavy_pdf: bool,
figure_rich_handbook: bool = False,
) -> 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:
return False
if scan_likely:
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:
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
@@ -181,7 +215,27 @@ def _should_use_page_image_mode(
image_count: int,
largest_ratio: float,
total_ratio: float,
figure_rich_handbook: bool = False,
) -> 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:
return False
if scan_likely:
@@ -201,9 +255,22 @@ def _should_use_page_image_mode(
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]:
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]
if text_heavy_pdf:
return [
@@ -305,8 +372,21 @@ def _render_page_png(
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"])
blocks: list[Block] = []
figure_rich_handbook = is_figure_rich_handbook(file_path.name)
try:
from pypdf import PdfReader
@@ -338,6 +418,7 @@ def run(input_data: dict, context: Context) -> list[Block]:
page_text_chars=len(text),
scan_likely=False,
text_heavy_pdf=False,
figure_rich_handbook=figure_rich_handbook,
):
continue
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 "")),
scan_likely=scan_likely,
text_heavy_pdf=text_heavy_pdf,
figure_rich_handbook=figure_rich_handbook,
)
]
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]]] = {}
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"]),
largest_ratio=float(stats["largest_ratio"]),
total_ratio=float(stats["total_ratio"]),
figure_rich_handbook=figure_rich_handbook,
)
if text:
@@ -476,6 +562,11 @@ def run(input_data: dict, context: Context) -> list[Block]:
context.extras["scan_likely"] = True
if text_heavy_pdf:
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:
context.extras["pdf_page_image_mode_pages"] = page_image_mode_pages
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.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['range'] == '30d'
assert data['by_user'][0]['username'] == 'report-user'
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):
with app.app_context():
db.session.add(Feedback(score=5))
@@ -21,3 +21,34 @@ def test_approve_and_reject_user(app):
user_service.reject_user(user.id)
db.session.refresh(user)
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