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,10 +1,16 @@
"""效能分析 API — ECharts 数据源(个人能力图谱 / 设备流转对比 / 筛选选项)"""
"""效能分析 API — ECharts 数据源(个人能力图谱 / 设备流转对比 / 筛选选项)
⚠️ 2026-09 起不再是「上帝视角」:所有端点都挂了 get_data_scope
结果按当前用户的业务分组范围过滤(超管不受限),且不再允许匿名访问。
"""
from datetime import datetime
from fastapi import APIRouter, Depends, Query
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.database import get_db
from app.core.deps import get_data_scope
from app.services.data_scope_service import DataScope
from app.services.analytics_service import (
get_capability_profile, CapabilityResponse,
get_flow_compare, FlowResponse,
@ -23,14 +29,15 @@ async def capability_profile(
until: str | None = Query(None, description="截止日期 ISO"),
mode: str = Query("workdays", description="耗时口径: workdays(工作小时,默认) / natural(自然小时)"),
db: AsyncSession = Depends(get_db),
scope: DataScope = Depends(get_data_scope),
):
"""个人能力图谱 — X 轴=设备身份证,分组柱状图(单台设备总耗时)。"""
"""个人能力图谱 — X 轴=设备身份证,分组柱状图(单台设备总耗时),按当前用户数据范围过滤"""
since_dt = datetime.fromisoformat(since) if since else None
until_dt = datetime.fromisoformat(until) if until else None
ids = [s.strip() for s in assignee_ids.split(",") if s.strip()] if assignee_ids else None
specs = [s.strip() for s in spec_models.split(",") if s.strip()] if spec_models else None
return await get_capability_profile(
db, assignee_ids=ids, spec_models=specs,
db, scope, assignee_ids=ids, spec_models=specs,
since=since_dt, until=until_dt, mode=mode,
)
@ -43,13 +50,14 @@ async def flow_compare(
since: str | None = Query(None, description="起始日期 ISO"),
until: str | None = Query(None, description="截止日期 ISO"),
db: AsyncSession = Depends(get_db),
scope: DataScope = Depends(get_data_scope),
):
"""设备流转对比 — 每台设备各操作人耗时(堆叠柱状,按人堆叠,识别瓶颈)。"""
"""设备流转对比 — 每台设备各操作人耗时(堆叠柱状,按人堆叠,识别瓶颈),按当前用户数据范围过滤"""
sns = [s.strip() for s in product_sns.split(",") if s.strip()] if product_sns else None
specs = [s.strip() for s in spec_models.split(",") if s.strip()] if spec_models else None
since_dt = datetime.fromisoformat(since) if since else None
until_dt = datetime.fromisoformat(until) if until else None
return await get_flow_compare(db, product_sns=sns, spec_models=specs, mode=mode, since=since_dt, until=until_dt)
return await get_flow_compare(db, scope, product_sns=sns, spec_models=specs, mode=mode, since=since_dt, until=until_dt)
@router.get("/options", response_model=AnalyticsOptions)
@ -57,11 +65,12 @@ async def analytics_options(
assignee_ids: str | None = Query(None, description="负责人ID逗号分隔联动过滤型号"),
spec_models: str | None = Query(None, description="规格型号,逗号分隔(联动过滤人员)"),
db: AsyncSession = Depends(get_db),
scope: DataScope = Depends(get_data_scope),
):
"""顶部筛选栏选项 — 负责人 + 规格型号,支持动态联动"""
"""顶部筛选栏选项 — 负责人 + 规格型号 + 设备字典,支持动态联动;按当前用户数据范围过滤"""
ids = [s.strip() for s in assignee_ids.split(",") if s.strip()] if assignee_ids else None
specs = [s.strip() for s in spec_models.split(",") if s.strip()] if spec_models else None
return await get_analytics_options(db, assignee_ids=ids, spec_models=specs)
return await get_analytics_options(db, scope, assignee_ids=ids, spec_models=specs)
@router.get("/device-records", response_model=list[DeviceRecord])
@ -69,7 +78,8 @@ async def device_records(
product_sn: str = Query(..., description="设备身份证"),
assignee_ids: str | None = Query(None, description="负责人ID逗号分隔可选用于过滤"),
db: AsyncSession = Depends(get_db),
scope: DataScope = Depends(get_data_scope),
):
"""某台设备的任务备注记录(含图片);可选按负责人过滤。"""
"""某台设备的任务备注记录(含图片);可选按负责人过滤;范围外设备返回空"""
ids = [s.strip() for s in assignee_ids.split(",") if s.strip()] if assignee_ids else None
return await get_device_records(db, product_sn, assignee_ids=ids)
return await get_device_records(db, scope, product_sn, assignee_ids=ids)

View File

@ -1,10 +1,18 @@
"""Dashboard API — 上帝视角(全厂数据,无用户过滤)"""
"""Dashboard API — 管理看板
⚠️ 2026-09 起不再是「上帝视角」:所有端点都挂了 get_data_scope
结果按当前用户的业务分组范围过滤(超管不受限)。
这同时把这些接口从**匿名可访问**变成了需要登录 —— 顺带堵上了
`/people-history/export` 匿名批量导出全员工时台账的已知风险。
"""
import io
from datetime import datetime
from fastapi import APIRouter, Depends, Query
from fastapi.responses import StreamingResponse
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.database import get_db
from app.core.deps import get_data_scope
from app.services.data_scope_service import DataScope
from app.core.time_utils import BEIJING_TZ
from app.services.dashboard_service import (
get_dashboard_stats, DashboardStats,
@ -41,16 +49,17 @@ async def dashboard_stats(
since: str | None = Query(None, description="起始日期 ISO 如 2026-08-01T00:00:00"),
until: str | None = Query(None, description="截止日期 ISO"),
db: AsyncSession = Depends(get_db),
scope: DataScope = Depends(get_data_scope),
):
"""
全局统计(上帝视角)。
统计概览(按当前用户的数据范围)。
时间筛选仅影响 COMPLETED / REJECTED 计数;
PENDING / WIP / 总数永远返回实时快照。
"""
since_dt = datetime.fromisoformat(since) if since else None
until_dt = datetime.fromisoformat(until) if until else None
return await get_dashboard_stats(db, since=since_dt, until=until_dt)
return await get_dashboard_stats(db, scope, since=since_dt, until=until_dt)
@router.get("/my-stats", response_model=MyStats)
@ -77,9 +86,10 @@ async def my_stats(
async def wip_tasks(
limit: int = Query(500, ge=1, le=1000, description="防御性安全上限;默认足以覆盖全部在制品"),
db: AsyncSession = Depends(get_db),
scope: DataScope = Depends(get_data_scope),
):
"""在制品看板 — 永远实时的 PENDING/WIP 任务(默认全量,不再按 20 条静默截断)"""
return await get_wip_tasks(db, limit)
return await get_wip_tasks(db, scope, limit)
@router.get("/completed-tasks", response_model=list[CompletedTask])
@ -88,11 +98,12 @@ async def completed_tasks(
until: str | None = Query(None, description="截止日期 ISO"),
limit: int = Query(200, ge=1, le=500),
db: AsyncSession = Depends(get_db),
scope: DataScope = Depends(get_data_scope),
):
"""流转完成率下钻 — 按时段查询已完成任务明细"""
since_dt = datetime.fromisoformat(since) if since else None
until_dt = datetime.fromisoformat(until) if until else None
return await get_completed_tasks(db, since=since_dt, until=until_dt, limit=limit)
return await get_completed_tasks(db, scope, since=since_dt, until=until_dt, limit=limit)
@router.get("/rejected-tasks", response_model=list[RejectedTask])
@ -101,11 +112,12 @@ async def rejected_tasks(
until: str | None = Query(None, description="截止日期 ISO"),
limit: int = Query(200, ge=1, le=500),
db: AsyncSession = Depends(get_db),
scope: DataScope = Depends(get_data_scope),
):
"""驳回/返工下钻 — 按时段查询被驳回任务明细(含返工去向)"""
since_dt = datetime.fromisoformat(since) if since else None
until_dt = datetime.fromisoformat(until) if until else None
return await get_rejected_tasks(db, since=since_dt, until=until_dt, limit=limit)
return await get_rejected_tasks(db, scope, since=since_dt, until=until_dt, limit=limit)
@router.get("/user-operations", response_model=list[UserOperation])
@ -113,11 +125,12 @@ async def user_operations(
since: str | None = Query(None, description="起始日期 ISO 如 2026-08-01T00:00:00"),
until: str | None = Query(None, description="截止日期 ISO"),
db: AsyncSession = Depends(get_db),
scope: DataScope = Depends(get_data_scope),
):
"""人员操作统计 — 按人聚合 接收/转交/上传备注 次数,按时段过滤"""
since_dt = datetime.fromisoformat(since) if since else None
until_dt = datetime.fromisoformat(until) if until else None
return await get_user_operations(db, since=since_dt, until=until_dt)
return await get_user_operations(db, scope, since=since_dt, until=until_dt)
@router.get("/user-operations/detail", response_model=list[OperationDetail])
@ -127,12 +140,13 @@ async def user_operations_detail(
since: str | None = Query(None, description="起始日期 ISO"),
until: str | None = Query(None, description="截止日期 ISO"),
db: AsyncSession = Depends(get_db),
scope: DataScope = Depends(get_data_scope),
):
"""人员操作明细下钻 — 某人在指定时段的接收/转交/上传备注明细"""
since_dt = datetime.fromisoformat(since) if since else None
until_dt = datetime.fromisoformat(until) if until else None
return await get_user_operation_detail(
db, user_id, action_type, since=since_dt, until=until_dt,
db, user_id, action_type, scope, since=since_dt, until=until_dt,
)
@ -142,11 +156,12 @@ async def wip_matrix(
since: str | None = Query(None, description="起始日期 ISO"),
until: str | None = Query(None, description="截止日期 ISO"),
db: AsyncSession = Depends(get_db),
scope: DataScope = Depends(get_data_scope),
):
"""生产分布透视表 — 规格型号 × 人员/工序 的设备数量交叉聚合(含已完成/已入库/已出库)"""
since_dt = datetime.fromisoformat(since) if since else None
until_dt = datetime.fromisoformat(until) if until else None
return await get_wip_matrix(db, dimension=dimension, since=since_dt, until=until_dt)
return await get_wip_matrix(db, scope, dimension=dimension, since=since_dt, until=until_dt)
@router.get("/wip-matrix/detail", response_model=list[WipMatrixDetailRow])
@ -156,19 +171,21 @@ async def wip_matrix_detail(
since: str | None = Query(None, description="起始日期 ISO"),
until: str | None = Query(None, description="截止日期 ISO"),
db: AsyncSession = Depends(get_db),
scope: DataScope = Depends(get_data_scope),
):
"""WIP 矩阵单元格下钻 — 返回某 规格型号×工序 交叉点下的设备明细"""
since_dt = datetime.fromisoformat(since) if since else None
until_dt = datetime.fromisoformat(until) if until else None
return await get_wip_matrix_detail(db, spec_model=spec, process=process, since=since_dt, until=until_dt)
return await get_wip_matrix_detail(db, scope, spec_model=spec, process=process, since=since_dt, until=until_dt)
@router.get("/people-workload", response_model=list[PersonWorkload])
async def people_workload(
db: AsyncSession = Depends(get_db),
scope: DataScope = Depends(get_data_scope),
):
"""人员负载 — 按负责人聚合当前在制品设备数(独立人员看板)"""
return await get_people_workload(db)
return await get_people_workload(db, scope)
@router.get("/people-history", response_model=list[PersonHistoryRecord])
@ -180,12 +197,13 @@ async def people_history(
product_sn: str | None = Query(None, description="身份证(模糊)"),
task_name: str | None = Query(None, description="任务名(模糊)"),
db: AsyncSession = Depends(get_db),
scope: DataScope = Depends(get_data_scope),
):
"""人员效能与工时台账 — 平铺 Task 明细,多维筛选 + 时间交集"""
since_dt = datetime.fromisoformat(since) if since else None
until_dt = datetime.fromisoformat(until) if until else None
return await get_people_history(
db, since=since_dt, until=until_dt,
db, scope, since=since_dt, until=until_dt,
assignee_id=assignee_id, spec_model=spec_model,
product_sn=product_sn, task_name=task_name,
)
@ -200,12 +218,17 @@ async def export_people_history(
product_sn: str | None = Query(None, description="身份证(模糊)"),
task_name: str | None = Query(None, description="任务名(模糊)"),
db: AsyncSession = Depends(get_db),
scope: DataScope = Depends(get_data_scope),
):
"""导出工时台账为 Excel与查询接口相同筛选条件"""
"""导出工时台账为 Excel与查询接口相同筛选条件
⚠️ 本接口此前是**匿名可访问**的,能批量导出全员工时台账。挂上 get_data_scope
后既要求登录、又按业务分组范围过滤 —— 这是本次改造顺带堵上的已知风险。
"""
since_dt = datetime.fromisoformat(since) if since else None
until_dt = datetime.fromisoformat(until) if until else None
records = await get_people_history(
db, since=since_dt, until=until_dt,
db, scope, since=since_dt, until=until_dt,
assignee_id=assignee_id, spec_model=spec_model,
product_sn=product_sn, task_name=task_name,
)
@ -247,11 +270,12 @@ async def dashboard_messages(
skip: int = Query(0, ge=0),
limit: int = Query(30, ge=1, le=200),
db: AsyncSession = Depends(get_db),
scope: DataScope = Depends(get_data_scope),
):
"""
协同留言搜索(上帝视角 — 全厂所有产品留言)。
协同留言搜索(按当前用户的数据范围过滤)。
关联 Product 表返回 serial_number + material_name
按时间倒序排列。
"""
return await search_product_messages(db, keyword=keyword, skip=skip, limit=limit)
return await search_product_messages(db, scope, keyword=keyword, skip=skip, limit=limit)

View File

@ -4,11 +4,16 @@
与 /dashboard 的区别:/dashboard 面向 PC 后台明细下钻(返回大列表),
/screen 只返回图表直接可用的扁平聚合数据,字段少、无分页、供高频轮询。
⚠️ 2026-09 起不再是「上帝视角」:三个端点都挂了 get_data_scope
结果按当前用户的业务分组范围过滤(超管不受限),且不再允许匿名访问。
"""
from fastapi import APIRouter, Depends, Query
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.database import get_db
from app.core.deps import get_data_scope
from app.services.data_scope_service import DataScope
from app.services.screen_service import (
get_monthly_metrics, MonthlyMetrics,
get_wip_distribution, WipDistributionResponse,
@ -19,34 +24,42 @@ router = APIRouter(prefix="/screen", tags=["大屏统计"])
@router.get("/monthly-metrics", response_model=MonthlyMetrics)
async def monthly_metrics(db: AsyncSession = Depends(get_db)):
async def monthly_metrics(
db: AsyncSession = Depends(get_db),
scope: DataScope = Depends(get_data_scope),
):
"""
当月吞吐 — 大屏顶部四张数字卡。
当月吞吐 — 大屏顶部四张数字卡(按当前用户的数据范围)
返回:本月生产流转 / 本月已入库 / 本月已出库 / 本月返厂回流。
统计区间为北京时间当月 1 日 00:00 至此刻。
"""
return await get_monthly_metrics(db)
return await get_monthly_metrics(db, scope)
@router.get("/wip-distribution", response_model=WipDistributionResponse)
async def wip_distribution(db: AsyncSession = Depends(get_db)):
async def wip_distribution(
db: AsyncSession = Depends(get_db),
scope: DataScope = Depends(get_data_scope),
):
"""
工序积压分布 — 当前未完结设备按 overall_status 聚合的**纯数量**。
工序积压分布 — 当前数据范围内未完结设备按 overall_status 聚合的**纯数量**。
返回固定阶段列表(含 0 值),保证柱状图类目稳定、不因缺数据而塌陷
返回固定阶段列表(含 0 值),保证柱状图类目稳定、不因缺数据而塌陷
工序柱本身也按数据范围裁剪(不属于本组阶段的工序不画)。
"""
return await get_wip_distribution(db)
return await get_wip_distribution(db, scope)
@router.get("/active-users", response_model=ActiveUsersResponse)
async def active_users(
top_n: int = Query(5, ge=1, le=20, description="返回的活跃人员数量"),
db: AsyncSession = Depends(get_db),
scope: DataScope = Depends(get_data_scope),
):
"""
本月系统使用活跃度排行 — 接收 / 转交 / 上传备注次数。
本月系统使用活跃度排行 — 接收 / 转交 / 上传备注次数(按当前用户的数据范围)
桥接 /dashboard/user-operations 的统计口径,仅返回本月确实有操作的人员。
"""
return await get_active_users(db, top_n=top_n)
return await get_active_users(db, scope, top_n=top_n)