feat(分组权限): 统计接口接入数据范围(dashboard / analytics / screen 共 20 个路由)

这三组接口此前是「上帝视角」且**匿名可访问**,现在全部挂 get_data_scope ——
既要求登录、又按业务分组范围过滤。顺带堵上了 AGENTS.md 点名的风险:
/dashboard/people-history/export 此前匿名即可批量导出全员工时台账。

dashboard(11 个函数 / 24 处注入)
· Product 主体 → product_where();Task、TaskLog 主体 → 先 join(Product) 再 task_where()
· 「卡片数字」与「下钻明细」成对出现的地方用同一谓词,避免「按钮显示 2、点开却是 0 条」
· get_user_operations 的 func.count() 改为 func.count(TaskLog.id) —— 显式化,不依赖
  join 形状(当前是 many-to-one 不会放大,但这样写更稳)
· unread_notif **刻意不过滤**:Notification.task_id 可空,按 Product 过滤会漏掉
  无任务关联的提醒(就地注释说明)
· get_my_stats 本轮不动 —— 它按本人归因,语义上不受分组影响

analytics(4 个函数 / 9 条语句)
· get_analytics_options 的 4 条独立语句全部处理 —— 它是筛选栏下拉的选项源,
  不过滤的话维修组能在下拉里看到生产组的人(最易漏的一处)
· get_device_records 的 product_id 查号是安全闸:范围外 SN 查不出 → 直接返回 []

screen(3 个函数)
· month_production **不做特判** —— 维修组的「本月生产数」本来就该是 0
· get_wip_distribution 按范围裁剪工序柱子,但坚持「恒 0 才裁、有数必现」,
  保证 total == sum(items) 在任何 scope 下都成立

实测(17 个端点):超管全部 200、匿名全部 401。
造 1 生产 + 1 售后产品后:
  超管   products=2 / wip-matrix 2 行 / options 2 个型号
  生产组 products=1 / wip-matrix 1 行 / options 1 个型号
  维修组 products=1 / wip-matrix 1 行 / options 1 个型号
列表与统计口径一致;未分组用户在过渡期开关下仍走 ungrouped_fallback。
测试数据已还原。
This commit is contained in:
2026-09-21 17:22:01 +08:00
parent 3c1c5d6fb5
commit 394e1e39c3
6 changed files with 360 additions and 88 deletions

View File

@ -1,4 +1,9 @@
"""Dashboard 统计服务 — 上帝视角(全厂全系统数据,不按用户过滤)"""
"""Dashboard 统计服务 — 按当前用户的**业务分组数据范围**过滤(超管不受限)
2026-09 起不再是「上帝视角」:统计函数一律接收调用方解析好的 DataScope,
查询里按 Product.lifecycle_phase 过滤(谓词只在 data_scope_service 生成,见该模块红线)。
唯一例外见 get_dashboard_stats 的 unread_notif(刻意不过滤,理由就地写明)。
"""
from datetime import datetime
from sqlalchemy import select, func, or_
from sqlalchemy.ext.asyncio import AsyncSession
@ -6,6 +11,7 @@ from pydantic import BaseModel
from app.core.config import settings
from app.core.lifecycle import normalize_after_sales_step
from app.services.data_scope_service import DataScope
# ============================================================
@ -242,11 +248,12 @@ def _rework_visible_condition(
async def get_dashboard_stats(
db: AsyncSession,
scope: DataScope,
since: datetime | None = None,
until: datetime | None = None,
) -> DashboardStats:
"""
上帝视角 — 全厂全系统统计。
看板统计 — 按当前用户的业务分组数据范围过滤。
时间筛选规则:
- PENDING / WIP / 总数:永远忽略时间筛选,返回实时快照。
@ -305,36 +312,63 @@ async def get_dashboard_stats(
select(Task.id).where(*done_time_conds).exists(),
)
p_unfinished = await db.scalar(select(func.count(Product.id)).where(not_finished)) or 0
p_progress = await db.scalar(
select(func.count(Product.id)).where(not_finished, has_active_task)
# 🚀 业务分组数据范围:产品三态计数均以 Product 为主体,直接挂 product_where
p_unfinished = await db.scalar(
select(func.count(Product.id)).where(not_finished, scope.product_where())
) or 0
p_progress = await db.scalar(
select(func.count(Product.id)).where(not_finished, has_active_task, scope.product_where())
) or 0
p_done = await db.scalar(
select(func.count(Product.id)).where(done_in_range, scope.product_where())
) or 0
p_done = await db.scalar(select(func.count(Product.id)).where(done_in_range)) or 0
# 待流转 = 未完结 - 在制;展示总数 = 未完结 + 所选时段已完结
# (三段互斥,保证进度条总和 = 展示总数)
p_pending = max(p_unfinished - p_progress, 0)
p_total = p_unfinished + p_done
# ── 任务实时快照(PENDING/WIP — 永远不过滤) ──
t_pending = await db.scalar(select(func.count(Task.id)).where(Task.status == TASK_STATUS_PENDING))
t_progress = await db.scalar(select(func.count(Task.id)).where(Task.status == TASK_STATUS_WIP))
# ── 任务实时快照(PENDING/WIP — 永不受时间筛选,但受业务分组数据范围约束) ──
# 🚀 业务分组数据范围:Task 为主体,先 join Product 再 task_where(tasks 表无 lifecycle_phase)
t_pending = await db.scalar(
select(func.count(Task.id))
.join(Product, Task.product_id == Product.id)
.where(Task.status == TASK_STATUS_PENDING, scope.task_where())
)
t_progress = await db.scalar(
select(func.count(Task.id))
.join(Product, Task.product_id == Product.id)
.where(Task.status == TASK_STATUS_WIP, scope.task_where())
)
# 返工数不再是无边界的全时段快照:未完结卡点永远计入,已了结的只算本月。
# 与 get_rejected_tasks 的 kind="rework" 共用同一份可见性条件,
# 保证「品质异常」卡片数字与点开后的明细条数对得上。
from app.services.screen_service import _month_bounds
month_start_utc, _, _ = _month_bounds()
# 🚀 业务分组数据范围:Task 为主体,先 join Product 再 task_where
t_rework = await db.scalar(
select(func.count(Task.id)).where(
select(func.count(Task.id))
.join(Product, Task.product_id == Product.id)
.where(
Task.is_rework.is_(True),
_rework_visible_condition(month_start_utc, since, until),
scope.task_where(),
)
)
# ── 任务已完成/驳回(时间可过滤) ──
t_done_q = select(func.count(Task.id)).where(Task.status == TASK_STATUS_COMPLETED)
t_rej_q = select(func.count(Task.id)).where(Task.status == TASK_STATUS_REJECTED)
# 🚀 业务分组数据范围:同上,两条独立语句各自挂 task_where
t_done_q = (
select(func.count(Task.id))
.join(Product, Task.product_id == Product.id)
.where(Task.status == TASK_STATUS_COMPLETED, scope.task_where())
)
t_rej_q = (
select(func.count(Task.id))
.join(Product, Task.product_id == Product.id)
.where(Task.status == TASK_STATUS_REJECTED, scope.task_where())
)
if since:
t_done_q = t_done_q.where(Task.completed_at >= since)
t_rej_q = t_rej_q.where(Task.completed_at >= since)
@ -348,10 +382,19 @@ async def get_dashboard_stats(
t_total = (t_pending or 0) + (t_progress or 0) + (t_done or 0) + (t_rejected or 0)
# ── 通知 & 留言(实时快照) ──
# 🚀 业务分组数据范围:**有意不过滤** —— Notification.task_id 允许为空
# (ondelete=SET NULL,且留言提醒类通知本就不挂任务),按 Product 过滤会
# 把这些「无任务关联」的提醒整条漏掉,未读角标会凭空少几颗。
# 这是刻意为之,不要「顺手补上」过滤。
unread_notif = await db.scalar(
select(func.count(Notification.id)).where(Notification.is_read.is_(False))
)
unread_msg = await db.scalar(select(func.count(ProductMessage.id)))
# 🚀 业务分组数据范围:ProductMessage.product_id 非空,join Product 后按阶段过滤
unread_msg = await db.scalar(
select(func.count(ProductMessage.id))
.join(Product, ProductMessage.product_id == Product.id)
.where(scope.product_where())
)
return DashboardStats(
products_total=p_total or 0,
@ -482,8 +525,8 @@ async def get_my_stats(
# 在制品看板(永远实时)
# ============================================================
async def get_wip_tasks(db: AsyncSession, limit: int = 500) -> list[WipTask]:
"""在制品看板 — 永远实时的 PENDING/WIP 任务。
async def get_wip_tasks(db: AsyncSession, scope: DataScope, limit: int = 500) -> list[WipTask]:
"""在制品看板 — 永远实时的 PENDING/WIP 任务(按业务分组数据范围过滤)。
默认返回**全部**活跃任务,limit 只是防御性安全上限。
@ -502,10 +545,14 @@ async def get_wip_tasks(db: AsyncSession, limit: int = 500) -> list[WipTask]:
holidays = {r[0] for r in hres}
# 不在 SQL 层做预取限制:排序在内存里按滞留时长进行,截断只作为上限保护
# 🚀 业务分组数据范围:已 join Product,直接挂 task_where
stmt = (
select(Task, Product.serial_number, Product.external_serial, Product.material_name, Product.spec_model)
.join(Product, Task.product_id == Product.id)
.where(Task.status.in_([TASK_STATUS_PENDING, TASK_STATUS_WIP]))
.where(
Task.status.in_([TASK_STATUS_PENDING, TASK_STATUS_WIP]),
scope.task_where(),
)
)
result = await db.execute(stmt)
rows = result.all()
@ -551,19 +598,24 @@ async def get_wip_tasks(db: AsyncSession, limit: int = 500) -> list[WipTask]:
async def get_completed_tasks(
db: AsyncSession,
scope: DataScope,
since: datetime | None = None,
until: datetime | None = None,
limit: int = 200,
) -> list[CompletedTask]:
"""按时段查询已完成任务明细(上帝视角),用于「流转完成率」卡片下钻。"""
"""按时段查询已完成任务明细(按业务分组数据范围过滤),用于「流转完成率」卡片下钻。
与 get_dashboard_stats 的 t_done 同一口径 + 同一数据范围,保证点进来条数对得上。
"""
from app.models.task import Task, TASK_STATUS_COMPLETED
from app.models.product import Product
from app.core.time_utils import BEIJING_TZ
# 🚀 业务分组数据范围:已 join Product,直接挂 task_where
stmt = (
select(Task, Product.serial_number, Product.external_serial, Product.material_name, Product.spec_model)
.join(Product, Task.product_id == Product.id)
.where(Task.status == TASK_STATUS_COMPLETED)
.where(Task.status == TASK_STATUS_COMPLETED, scope.task_where())
)
if since:
stmt = stmt.where(Task.completed_at >= since)
@ -608,11 +660,15 @@ async def get_completed_tasks(
async def get_rejected_tasks(
db: AsyncSession,
scope: DataScope,
since: datetime | None = None,
until: datetime | None = None,
limit: int = 200,
) -> list[RejectedTask]:
"""查询驳回/返工任务明细(上帝视角),用于「驳回/返工」卡片下钻。
"""查询驳回/返工任务明细(按业务分组数据范围过滤),用于「驳回/返工」卡片下钻。
⚠️ 两条语句(已驳回 / 返工)都要挂同一个 task_where,否则与
get_dashboard_stats 的 tasks_rejected + tasks_rework 卡片数字对不上。
返回两类(与卡片数字 tasks_rejected + tasks_rework 口径一致):
- kind="rejected":被驳回任务,按 completed_at 时间过滤
@ -641,10 +697,11 @@ async def get_rejected_tasks(
return dt.isoformat()
# ── 1. 已驳回任务(按时间过滤)──
# 🚀 业务分组数据范围:已 join Product,直接挂 task_where
stmt = (
select(Task, Product.serial_number, Product.external_serial, Product.material_name, Product.spec_model)
.join(Product, Task.product_id == Product.id)
.where(Task.status == TASK_STATUS_REJECTED)
.where(Task.status == TASK_STATUS_REJECTED, scope.task_where())
)
if since:
stmt = stmt.where(Task.completed_at >= since)
@ -659,6 +716,7 @@ async def get_rejected_tasks(
# 统一约束 —— 未完结卡点永远展示,已了结的仅限本月(详见该函数说明)。
from app.services.screen_service import _month_bounds
month_start_utc, _, _ = _month_bounds()
# 🚀 业务分组数据范围:同口径挂 task_where,保证与卡片 tasks_rework 一致
rework_stmt = (
select(Task, Product.serial_number, Product.external_serial, Product.material_name, Product.spec_model)
.join(Product, Task.product_id == Product.id)
@ -666,6 +724,7 @@ async def get_rejected_tasks(
Task.is_rework.is_(True),
Task.status != TASK_STATUS_REJECTED,
_rework_visible_condition(month_start_utc, since, until),
scope.task_where(),
)
.order_by(Task.created_at.desc())
.limit(limit)
@ -710,9 +769,16 @@ async def get_rejected_tasks(
rework_candidates: dict = {}
product_ids = {t.product_id for t, *_ in rejected_rows if t.product_id}
if product_ids:
# 🚀 业务分组数据范围:本查询也是 Task 主体,一并挂 task_where
# (product_ids 已来自上方受限结果,这里只是把口径写全,结果集不变)
cand_rows = await db.execute(
select(Task.parent_task_id, Task.product_id, Task.created_at, Task.assignee_id)
.where(Task.is_rework.is_(True), Task.product_id.in_(product_ids))
.join(Product, Task.product_id == Product.id)
.where(
Task.is_rework.is_(True),
Task.product_id.in_(product_ids),
scope.task_where(),
)
.order_by(Task.created_at.asc())
)
for parent_id, prod_id, created_at, assignee_id in cand_rows.all():
@ -787,10 +853,11 @@ async def get_rejected_tasks(
async def get_user_operations(
db: AsyncSession,
scope: DataScope,
since: datetime | None = None,
until: datetime | None = None,
) -> list[UserOperation]:
"""上帝视角 — 统计**全部人员**的操作次数(按时段过滤)。
"""统计**当前数据范围内人员**的操作次数(按时段过滤)。
返回本部门(ORG_DEPARTMENT)全部人员(该时段无操作的计 0),并追加有操作
记录但不在人员清单中的账号(如历史/已离职)。
@ -803,17 +870,24 @@ async def get_user_operations(
"""
from app.models.task_log import TaskLog
from app.models.task import Task, TaskRecord
from app.models.product import Product
from app.core.mom_database import MomSessionLocal
from sqlalchemy import text, or_
# ── 1. 接收 / 转交(task_logs 按 operator_id 聚合)──
rcv = func.count().filter(TaskLog.action_type == "receive")
cpl = func.count().filter(TaskLog.action_type == "complete")
# ⚠️ 必须指明具体列:为接入数据范围本查询已 join Product,若写裸 count()
# 会按 join 出的行数重复计数,卡片数字虚高。
rcv = func.count(TaskLog.id).filter(TaskLog.action_type == "receive")
cpl = func.count(TaskLog.id).filter(TaskLog.action_type == "complete")
# 🚀 业务分组数据范围:TaskLog → Task → Product 两级 join 后挂 task_where
stmt = (
select(TaskLog.operator_id, rcv.label("receive"), cpl.label("complete"))
.join(Task, TaskLog.task_id == Task.id)
.join(Product, Task.product_id == Product.id)
.where(
TaskLog.action_type.in_(["receive", "complete"]),
TaskLog.operator_id.isnot(None),
scope.task_where(),
)
.group_by(TaskLog.operator_id)
)
@ -825,12 +899,15 @@ async def get_user_operations(
op_map = {r[0]: (r[1] or 0, r[2] or 0) for r in op_rows}
# ── 2. 上传备注(task_records 按任务 assignee 归因,排除系统自动备注)──
# 🚀 业务分组数据范围:TaskRecord 经 Task 关联到 Product 后挂 task_where
rcd_stmt = (
select(Task.assignee_id, func.count(TaskRecord.id))
.join(Task, TaskRecord.task_id == Task.id)
.join(Product, Task.product_id == Product.id)
.where(
Task.assignee_id.isnot(None),
or_(TaskRecord.remark.is_(None), ~TaskRecord.remark.like("[%")),
scope.task_where(),
)
.group_by(Task.assignee_id)
)
@ -896,11 +973,12 @@ async def get_user_operations(
async def get_wip_matrix(
db: AsyncSession,
scope: DataScope,
dimension: str = "assignee",
since: datetime | None = None,
until: datetime | None = None,
) -> list[WipMatrixRow]:
"""生产分布透视表:Y=规格型号,X=人员 或 工序,单元格=设备数量。
"""生产分布透视表:Y=规格型号,X=人员 或 工序,单元格=设备数量(按业务分组数据范围过滤)。
核心口径:**每台设备只统计一次**,按它「当前所处工序」归属——
1. 取该设备最新的一条主分支任务(parent_task_id IS NULL 或 TRANSFER/RECOVERY)
@ -927,6 +1005,9 @@ async def get_wip_matrix(
_ActiveTask = aliased(Task, name="active_task")
# 每台设备按主任务创建时间倒序,取第一条即「最新主任务」
# 🚀 业务分组数据范围:主体是 Product(outerjoin tasks 不影响主体),挂 product_where。
# 矩阵格子的设备数与被过滤掉的设备在这里一次性拦掉,下钻(get_wip_matrix_detail)
# 必须用同一谓词,否则「格子里有数、点进去是空的」。
result = await db.execute(
select(
Product.id,
@ -957,7 +1038,8 @@ async def get_wip_matrix(
Task.id.is_(None), # 🔧 允许该产品完全没有任务记录(新建档/待接收)
Task.parent_task_id.is_(None),
Task.task_type.in_(["TRANSFER", "RECOVERY", "WAREHOUSE"]),
)
),
scope.product_where(), # 🚀 业务分组数据范围
)
.order_by(Product.id, Task.created_at.desc())
)
@ -1104,6 +1186,7 @@ async def get_wip_matrix(
async def get_wip_matrix_detail(
db: AsyncSession,
scope: DataScope,
spec_model: str,
process: str,
since: datetime | None = None,
@ -1113,6 +1196,7 @@ async def get_wip_matrix_detail(
口径与 get_wip_matrix 完全一致:每台设备取最新一条主分支任务,
按其在库三态(已完成/已入库/已出库)或工序名归类到 process。
数据范围也必须与 get_wip_matrix 同谓词,否则格子里有数、点进来却是空的。
"""
from datetime import timezone as dt_timezone
from sqlalchemy.orm import aliased
@ -1157,7 +1241,8 @@ async def get_wip_matrix_detail(
Task.id.is_(None), # 🔧 允许该产品完全没有任务记录(新建档/待接收)
Task.parent_task_id.is_(None),
Task.task_type.in_(["TRANSFER", "RECOVERY", "WAREHOUSE"]),
)
),
scope.product_where(), # 🚀 业务分组数据范围(与 get_wip_matrix 同谓词)
)
.order_by(Product.id, Task.created_at.desc())
)
@ -1269,13 +1354,16 @@ async def get_wip_matrix_detail(
import uuid as uuid_mod
from sqlalchemy import func as sa_func
uuid_list = [uuid_mod.UUID(m.product_id) for m in matched]
# 🚀 业务分组数据范围:本查询也是 Task 主体,一并挂 task_where
# (uuid_list 已来自上方受限结果,这里只是把口径写全,结果集不变)
range_rows = (await db.execute(
select(
Task.product_id,
sa_func.min(sa_func.coalesce(Task.received_at, Task.created_at)).label("t0"),
sa_func.max(sa_func.coalesce(Task.completed_at, now)).label("tmax"),
)
.where(Task.product_id.in_(uuid_list))
.join(Product, Task.product_id == Product.id)
.where(Task.product_id.in_(uuid_list), scope.task_where())
.group_by(Task.product_id)
)).all()
row_by_pid = {m.product_id: m for m in matched}
@ -1297,10 +1385,13 @@ async def get_user_operation_detail(
db: AsyncSession,
user_id: str,
action_type: str,
scope: DataScope,
since: datetime | None = None,
until: datetime | None = None,
) -> list[OperationDetail]:
"""查询某人在指定时段内的某类操作明细。
"""查询某人在指定时段内的某类操作明细(按业务分组数据范围过滤)。
与 get_user_operations 的数字同口径,否则「点数字看到的条数」对不上。
action_type:
- receive: 接收(task_logs.action_type='receive')
@ -1326,11 +1417,16 @@ async def get_user_operation_detail(
if action_type in ("receive", "transfer"):
act = "receive" if action_type == "receive" else "complete"
# 🚀 业务分组数据范围:TaskLog 已 join Task 与 Product,直接挂 task_where
stmt = (
select(TaskLog.created_at, Task.task_name, Product.serial_number, Product.material_name, TaskLog.remark)
.join(Task, TaskLog.task_id == Task.id)
.join(Product, Task.product_id == Product.id)
.where(TaskLog.operator_id == user_id, TaskLog.action_type == act)
.where(
TaskLog.operator_id == user_id,
TaskLog.action_type == act,
scope.task_where(),
)
.order_by(TaskLog.created_at.desc())
)
if since:
@ -1354,6 +1450,7 @@ async def get_user_operation_detail(
.where(
Task.assignee_id == user_id,
or_(TaskRecord.remark.is_(None), ~TaskRecord.remark.like("[%")),
scope.task_where(), # 🚀 业务分组数据范围(已 join Product)
)
.order_by(TaskRecord.created_at.desc())
)
@ -1377,8 +1474,11 @@ async def get_user_operation_detail(
# 人员负载(按人聚合在制品设备 — 独立「人员看板」)
# ============================================================
async def get_people_workload(db: AsyncSession) -> list[PersonWorkload]:
"""上帝视角 — 按负责人聚合当前在制品设备(WIP/PENDING 任务,product 去重,含滞留时长)。"""
async def get_people_workload(db: AsyncSession, scope: DataScope) -> list[PersonWorkload]:
"""按负责人聚合当前在制品设备(WIP/PENDING 任务,product 去重,含滞留时长)。
按业务分组数据范围过滤。
"""
from app.models.task import Task, TASK_STATUS_PENDING, TASK_STATUS_WIP
from app.models.product import Product
from app.models.holiday import Holiday
@ -1399,6 +1499,7 @@ async def get_people_workload(db: AsyncSession) -> list[PersonWorkload]:
.where(
Task.status.in_([TASK_STATUS_PENDING, TASK_STATUS_WIP]),
Task.assignee_id.isnot(None),
scope.task_where(), # 🚀 业务分组数据范围(已 join Product)
)
.order_by(Task.assignee_id, Product.created_at.desc())
)
@ -1473,6 +1574,7 @@ async def get_people_workload(db: AsyncSession) -> list[PersonWorkload]:
async def get_people_history(
db: AsyncSession,
scope: DataScope,
since: datetime | None = None,
until: datetime | None = None,
assignee_id: str | None = None,
@ -1480,7 +1582,12 @@ async def get_people_history(
product_sn: str | None = None,
task_name: str | None = None,
) -> list[PersonHistoryRecord]:
"""上帝视角 — 人员效能与工时台账(平铺 Task 明细,含 WIP/PENDING/COMPLETED)。"""
"""人员效能与工时台账(平铺 Task 明细,含 WIP/PENDING/COMPLETED,按业务分组数据范围过滤)。
⚠️ 两个子查询(最新有效备注 / 记录总数)只扫 task_records,靠下面的 outerjoin
挂到本语句的 Task 上,会被主查询的 WHERE(含数据范围谓词)一并收窄,
故无需在子查询内部再过滤一次。
"""
from app.models.task import Task, TASK_STATUS_WIP, TASK_STATUS_PENDING, TASK_STATUS_COMPLETED
from app.models.product import Product
from app.core.time_utils import get_beijing_time, BEIJING_TZ, to_beijing, working_duration_hours
@ -1554,6 +1661,7 @@ async def get_people_history(
.where(
Task.status.in_([TASK_STATUS_WIP, TASK_STATUS_PENDING, TASK_STATUS_COMPLETED]),
Task.assignee_id.isnot(None),
scope.task_where(), # 🚀 业务分组数据范围(已 join Product)
)
)
@ -1642,12 +1750,13 @@ async def get_people_history(
async def search_product_messages(
db: AsyncSession,
scope: DataScope,
keyword: str = "",
skip: int = 0,
limit: int = 50,
) -> ProductMessageList:
"""
上帝视角 — 全厂所有产品的协同留言。
协同留言搜索 — 只返回当前业务分组数据范围内产品的留言。
关联链: ProductMessage → Product → (material_name, serial_number)
搜索支持: SN码、物料名称、留言人
@ -1658,9 +1767,12 @@ async def search_product_messages(
from app.core.time_utils import BEIJING_TZ
# 基础查询 — 同时取出 16位追溯码 + 业务序列号
# 🚀 业务分组数据范围:已 join Product,直接挂 product_where
# (下方 total 由本 stmt 派生子查询,自动继承同一谓词,条数不会对不上)
stmt = (
select(ProductMessage, Product.serial_number, Product.material_name, Product.external_serial)
.join(Product, ProductMessage.product_id == Product.id)
.where(scope.product_where())
)
# 关键词搜索