Files
track/backend/app/api/v1/endpoints/dashboard.py

258 lines
11 KiB
Python
Raw Normal View History

"""Dashboard API — 上帝视角(全厂数据,无用户过滤)"""
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
feat: 新增个人效能统计接口 /dashboard/my-stats(支持自选时段) 移动端「个人中心 → 工作统计」的数据源。现有接口拿不到这份数据: /dashboard/people-history 支持 assignee_id 但只返回 WIP/PENDING/COMPLETED, 不含 REJECTED;/dashboard/rejected-tasks 则根本没有 assignee_id 参数 —— 「今日被驳回数」按现有接口无论如何都过滤不到个人。故补一个薄桥接端点。 服务端 get_my_stats(db, assignee_id, since, until) 返回两组指标: 生产战绩(按 Task.assignee_id 归因) - tasks_completed / tasks_rejected:status 判定 + completed_at 落在区间, 与 get_dashboard_stats 的 t_done_q 同一口径,只多了 assignee_id 过滤 - products_touched:按 product_id 去重,同一台设备做多道工序只算一台 操作统计(与 PC /dashboard/user-operations 严格同口径) - receive/transfer:task_logs 的 receive / complete,按 operator_id 归因 - record:task_records 按 Task.assignee_id 归因,排除 '[' 开头的系统自动备注 - 前两项归因 operator_id、第三项归因 assignee_id 是 PC 端既有口径, 此处刻意保持一致,便于工人自查的数与主管看到的面板对得上 端点侧新增 _parse_bound():裸时间字符串(无时区偏移)按北京时间解释, 否则会被当作服务器本地时间,边界整体偏 8 小时,出现「选了今日却统计到 昨天下午」。since/until 缺省为「本月 1 日 ~ 此刻」。
2026-09-15 15:51:34 +08:00
from app.core.time_utils import BEIJING_TZ
from app.services.dashboard_service import (
get_dashboard_stats, DashboardStats,
feat: 新增个人效能统计接口 /dashboard/my-stats(支持自选时段) 移动端「个人中心 → 工作统计」的数据源。现有接口拿不到这份数据: /dashboard/people-history 支持 assignee_id 但只返回 WIP/PENDING/COMPLETED, 不含 REJECTED;/dashboard/rejected-tasks 则根本没有 assignee_id 参数 —— 「今日被驳回数」按现有接口无论如何都过滤不到个人。故补一个薄桥接端点。 服务端 get_my_stats(db, assignee_id, since, until) 返回两组指标: 生产战绩(按 Task.assignee_id 归因) - tasks_completed / tasks_rejected:status 判定 + completed_at 落在区间, 与 get_dashboard_stats 的 t_done_q 同一口径,只多了 assignee_id 过滤 - products_touched:按 product_id 去重,同一台设备做多道工序只算一台 操作统计(与 PC /dashboard/user-operations 严格同口径) - receive/transfer:task_logs 的 receive / complete,按 operator_id 归因 - record:task_records 按 Task.assignee_id 归因,排除 '[' 开头的系统自动备注 - 前两项归因 operator_id、第三项归因 assignee_id 是 PC 端既有口径, 此处刻意保持一致,便于工人自查的数与主管看到的面板对得上 端点侧新增 _parse_bound():裸时间字符串(无时区偏移)按北京时间解释, 否则会被当作服务器本地时间,边界整体偏 8 小时,出现「选了今日却统计到 昨天下午」。since/until 缺省为「本月 1 日 ~ 此刻」。
2026-09-15 15:51:34 +08:00
get_my_stats, MyStats,
get_wip_tasks, WipTask,
get_completed_tasks, CompletedTask,
get_rejected_tasks, RejectedTask,
get_user_operations, UserOperation,
get_user_operation_detail, OperationDetail,
get_wip_matrix, WipMatrixRow,
get_wip_matrix_detail, WipMatrixDetailRow,
get_people_workload, PersonWorkload,
get_people_history, PersonHistoryRecord,
search_product_messages, ProductMessageList,
)
router = APIRouter(prefix="/dashboard", tags=["管理看板"])
feat: 新增个人效能统计接口 /dashboard/my-stats(支持自选时段) 移动端「个人中心 → 工作统计」的数据源。现有接口拿不到这份数据: /dashboard/people-history 支持 assignee_id 但只返回 WIP/PENDING/COMPLETED, 不含 REJECTED;/dashboard/rejected-tasks 则根本没有 assignee_id 参数 —— 「今日被驳回数」按现有接口无论如何都过滤不到个人。故补一个薄桥接端点。 服务端 get_my_stats(db, assignee_id, since, until) 返回两组指标: 生产战绩(按 Task.assignee_id 归因) - tasks_completed / tasks_rejected:status 判定 + completed_at 落在区间, 与 get_dashboard_stats 的 t_done_q 同一口径,只多了 assignee_id 过滤 - products_touched:按 product_id 去重,同一台设备做多道工序只算一台 操作统计(与 PC /dashboard/user-operations 严格同口径) - receive/transfer:task_logs 的 receive / complete,按 operator_id 归因 - record:task_records 按 Task.assignee_id 归因,排除 '[' 开头的系统自动备注 - 前两项归因 operator_id、第三项归因 assignee_id 是 PC 端既有口径, 此处刻意保持一致,便于工人自查的数与主管看到的面板对得上 端点侧新增 _parse_bound():裸时间字符串(无时区偏移)按北京时间解释, 否则会被当作服务器本地时间,边界整体偏 8 小时,出现「选了今日却统计到 昨天下午」。since/until 缺省为「本月 1 日 ~ 此刻」。
2026-09-15 15:51:34 +08:00
def _parse_bound(value: str | None) -> datetime | None:
"""解析 ISO 时间边界。
裸时间(无时区偏移)按**北京时间**解释 —— 否则会被当作服务器本地时间,
在边界上整体偏移 8 小时,出现「选了今日却统计到昨天下午」这类错位。
"""
if not value:
return None
dt = datetime.fromisoformat(value)
return dt.replace(tzinfo=BEIJING_TZ) if dt.tzinfo is None else dt
@router.get("/stats", response_model=DashboardStats)
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),
):
"""
全局统计(上帝视角)。
时间筛选仅影响 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)
feat: 新增个人效能统计接口 /dashboard/my-stats(支持自选时段) 移动端「个人中心 → 工作统计」的数据源。现有接口拿不到这份数据: /dashboard/people-history 支持 assignee_id 但只返回 WIP/PENDING/COMPLETED, 不含 REJECTED;/dashboard/rejected-tasks 则根本没有 assignee_id 参数 —— 「今日被驳回数」按现有接口无论如何都过滤不到个人。故补一个薄桥接端点。 服务端 get_my_stats(db, assignee_id, since, until) 返回两组指标: 生产战绩(按 Task.assignee_id 归因) - tasks_completed / tasks_rejected:status 判定 + completed_at 落在区间, 与 get_dashboard_stats 的 t_done_q 同一口径,只多了 assignee_id 过滤 - products_touched:按 product_id 去重,同一台设备做多道工序只算一台 操作统计(与 PC /dashboard/user-operations 严格同口径) - receive/transfer:task_logs 的 receive / complete,按 operator_id 归因 - record:task_records 按 Task.assignee_id 归因,排除 '[' 开头的系统自动备注 - 前两项归因 operator_id、第三项归因 assignee_id 是 PC 端既有口径, 此处刻意保持一致,便于工人自查的数与主管看到的面板对得上 端点侧新增 _parse_bound():裸时间字符串(无时区偏移)按北京时间解释, 否则会被当作服务器本地时间,边界整体偏 8 小时,出现「选了今日却统计到 昨天下午」。since/until 缺省为「本月 1 日 ~ 此刻」。
2026-09-15 15:51:34 +08:00
@router.get("/my-stats", response_model=MyStats)
async def my_stats(
assignee_id: str = Query(..., description="负责人ID(移动端传当前登录用户 username)"),
since: str | None = Query(None, description="起始时间 ISO(含时区偏移,如 2026-09-01T00:00:00+08:00);缺省=本月 1 日"),
until: str | None = Query(None, description="截止时间 ISO(含时区偏移);缺省=此刻"),
db: AsyncSession = Depends(get_db),
):
"""
一线工人个人效能 — 移动端「工作统计」页,支持自选时段。
- 生产战绩(完成 / 被驳回 / 参与产品)按本人名下任务归因;
- 操作统计(接收 / 转交 / 上传备注)与 PC /dashboard/user-operations 严格同口径,
工人自查的数与主管看到的面板对得上。
⚠️ since/until 必须带时区偏移。移动端发的是北京时间 (+08:00),
不带偏移的裸字符串会被当成"本地时间"导致边界偏移 8 小时。
"""
return await get_my_stats(db, assignee_id, since=_parse_bound(since), until=_parse_bound(until))
@router.get("/wip-tasks", response_model=list[WipTask])
async def wip_tasks(
feat: 生产看板多维度重构(全量在制品、时间维度联动、口径提示) 本次只含后端看板接口与 PC 端页面。移动端的体验优化已在之前的 12 个提交中 入库,不在本提交范围内。 后端 · 服务层 dashboard_service.py - 在制品列表不再按 20 条静默截断:此前 `.limit(limit*2)` 预取再排序切片, 前端又拿数组长度当总数,表现为「卡片 23、列表却写共 20 个」的数据被吞。 现默认返回全量,limit 降级为防御性上限 - 产品流转「已完结」接入右上角时间筛选(since/until),废弃硬编码「本月」。 此前选「今天」也会看到整月产出,业务语义分裂;待流转/流转中仍为实时快照。 Product 表无 completed_at,以名下工序的完成时间锚定「完结时刻」 - 返工任务可见性:未完结卡点永远展示,已了结的仅限本月,且与卡片数字共用 同一份条件,避免「按钮显示 2、点开共 0 条」 - 驳回明细的「返工给」改为真实溯源:直接查派生出的返工任务当前 assignee_id, 不再复刻 reject_task 的推算逻辑(返工任务事后被转交时会显示旧名字) 后端 · 接口层 dashboard.py - /wip-tasks 的 limit 默认 20→500、上限 100→1000 - /my-stats 支持 since/until,新增接收/转交/上传备注口径(与 PC 人员操作统计 逐字段交叉验证一致) PC 端 - AdminDashboard: 在制品计数绑定真实总数并加截断提示、列表改为容器内滚动; 驳回明细只展示「已驳回」行(返工行不再独立成行,其信息已由「返工给」承载); 「待流转」「待接收」图例新增口径 Tooltip,消除「产品数 > 任务数」的误解; 移除已失真的时间筛选提示条 - App.tsx: dayjs 中文 locale 上提到应用根。此前散落在 AdminPeoplePage / AnalyticsDashboard 两个页面里,而路由是 lazy 分割的 —— 直接打开概览页时 那两个模块未加载,日期面板就露出 Sep/Su/Mo - AdminPeoplePage / AnalyticsDashboard: 移除重复的页面级 locale 设置 - dashboardApi.ts: fetchWipTasks 默认值同步为 500
2026-09-16 14:29:56 +08:00
limit: int = Query(500, ge=1, le=1000, description="防御性安全上限;默认足以覆盖全部在制品"),
db: AsyncSession = Depends(get_db),
):
feat: 生产看板多维度重构(全量在制品、时间维度联动、口径提示) 本次只含后端看板接口与 PC 端页面。移动端的体验优化已在之前的 12 个提交中 入库,不在本提交范围内。 后端 · 服务层 dashboard_service.py - 在制品列表不再按 20 条静默截断:此前 `.limit(limit*2)` 预取再排序切片, 前端又拿数组长度当总数,表现为「卡片 23、列表却写共 20 个」的数据被吞。 现默认返回全量,limit 降级为防御性上限 - 产品流转「已完结」接入右上角时间筛选(since/until),废弃硬编码「本月」。 此前选「今天」也会看到整月产出,业务语义分裂;待流转/流转中仍为实时快照。 Product 表无 completed_at,以名下工序的完成时间锚定「完结时刻」 - 返工任务可见性:未完结卡点永远展示,已了结的仅限本月,且与卡片数字共用 同一份条件,避免「按钮显示 2、点开共 0 条」 - 驳回明细的「返工给」改为真实溯源:直接查派生出的返工任务当前 assignee_id, 不再复刻 reject_task 的推算逻辑(返工任务事后被转交时会显示旧名字) 后端 · 接口层 dashboard.py - /wip-tasks 的 limit 默认 20→500、上限 100→1000 - /my-stats 支持 since/until,新增接收/转交/上传备注口径(与 PC 人员操作统计 逐字段交叉验证一致) PC 端 - AdminDashboard: 在制品计数绑定真实总数并加截断提示、列表改为容器内滚动; 驳回明细只展示「已驳回」行(返工行不再独立成行,其信息已由「返工给」承载); 「待流转」「待接收」图例新增口径 Tooltip,消除「产品数 > 任务数」的误解; 移除已失真的时间筛选提示条 - App.tsx: dayjs 中文 locale 上提到应用根。此前散落在 AdminPeoplePage / AnalyticsDashboard 两个页面里,而路由是 lazy 分割的 —— 直接打开概览页时 那两个模块未加载,日期面板就露出 Sep/Su/Mo - AdminPeoplePage / AnalyticsDashboard: 移除重复的页面级 locale 设置 - dashboardApi.ts: fetchWipTasks 默认值同步为 500
2026-09-16 14:29:56 +08:00
"""在制品看板 — 永远实时的 PENDING/WIP 任务(默认全量,不再按 20 条静默截断)"""
return await get_wip_tasks(db, limit)
@router.get("/completed-tasks", response_model=list[CompletedTask])
async def completed_tasks(
since: str | None = Query(None, description="起始日期 ISO 如 2026-08-01T00:00:00"),
until: str | None = Query(None, description="截止日期 ISO"),
limit: int = Query(200, ge=1, le=500),
db: AsyncSession = Depends(get_db),
):
"""流转完成率下钻 — 按时段查询已完成任务明细"""
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)
@router.get("/rejected-tasks", response_model=list[RejectedTask])
async def rejected_tasks(
since: str | None = Query(None, description="起始日期 ISO 如 2026-08-01T00:00:00"),
until: str | None = Query(None, description="截止日期 ISO"),
limit: int = Query(200, ge=1, le=500),
db: AsyncSession = Depends(get_db),
):
"""驳回/返工下钻 — 按时段查询被驳回任务明细(含返工去向)"""
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)
@router.get("/user-operations", response_model=list[UserOperation])
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),
):
"""人员操作统计 — 按人聚合 接收/转交/上传备注 次数,按时段过滤"""
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)
@router.get("/user-operations/detail", response_model=list[OperationDetail])
async def user_operations_detail(
user_id: str = Query(..., description="人员ID(username)"),
action_type: str = Query(..., description="操作类型: receive/transfer/record"),
since: str | None = Query(None, description="起始日期 ISO"),
until: str | None = Query(None, description="截止日期 ISO"),
db: AsyncSession = Depends(get_db),
):
"""人员操作明细下钻 — 某人在指定时段的接收/转交/上传备注明细"""
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,
)
@router.get("/wip-matrix", response_model=list[WipMatrixRow])
async def wip_matrix(
dimension: str = Query("assignee", description="聚合维度: assignee(人员) / task_name(工序)"),
since: str | None = Query(None, description="起始日期 ISO"),
until: str | None = Query(None, description="截止日期 ISO"),
db: AsyncSession = Depends(get_db),
):
"""生产分布透视表 — 规格型号 × 人员/工序 的设备数量交叉聚合(含已完成/已入库/已出库)"""
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)
@router.get("/wip-matrix/detail", response_model=list[WipMatrixDetailRow])
async def wip_matrix_detail(
spec: str = Query(..., description="规格型号"),
process: str = Query(..., description="当前工序(dimension_key)"),
since: str | None = Query(None, description="起始日期 ISO"),
until: str | None = Query(None, description="截止日期 ISO"),
db: AsyncSession = Depends(get_db),
):
"""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)
@router.get("/people-workload", response_model=list[PersonWorkload])
async def people_workload(
db: AsyncSession = Depends(get_db),
):
"""人员负载 — 按负责人聚合当前在制品设备数(独立人员看板)"""
return await get_people_workload(db)
@router.get("/people-history", response_model=list[PersonHistoryRecord])
async def people_history(
since: str | None = Query(None, description="起始日期 ISO"),
until: str | None = Query(None, description="截止日期 ISO"),
assignee_id: str | None = Query(None, description="负责人ID(精确)"),
spec_model: str | None = Query(None, description="规格型号(模糊)"),
product_sn: str | None = Query(None, description="身份证(模糊)"),
task_name: str | None = Query(None, description="任务名(模糊)"),
db: AsyncSession = Depends(get_db),
):
"""人员效能与工时台账 — 平铺 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,
assignee_id=assignee_id, spec_model=spec_model,
product_sn=product_sn, task_name=task_name,
)
@router.get("/people-history/export")
async def export_people_history(
since: str | None = Query(None, description="起始日期 ISO"),
until: str | None = Query(None, description="截止日期 ISO"),
assignee_id: str | None = Query(None, description="负责人ID(精确)"),
spec_model: str | None = Query(None, description="规格型号(模糊)"),
product_sn: str | None = Query(None, description="身份证(模糊)"),
task_name: str | None = Query(None, description="任务名(模糊)"),
db: AsyncSession = Depends(get_db),
):
"""导出工时台账为 Excel(与查询接口相同筛选条件)"""
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,
assignee_id=assignee_id, spec_model=spec_model,
product_sn=product_sn, task_name=task_name,
)
import csv
output = io.StringIO()
writer = csv.writer(output)
writer.writerow(["状态", "负责人", "身份证", "业务序列号", "产品名称", "规格型号", "任务名", "开始时间", "结束时间", "总耗时(小时)", "最新有效备注"])
status_label = {"WIP": "进行中", "PENDING": "待接收", "COMPLETED": "已完成"}
for r in records:
writer.writerow([
status_label.get(r.status, r.status),
r.assignee_name,
r.product_sn,
r.external_serial or "",
r.material_name,
r.spec_model,
r.task_name,
r.received_at or "",
r.completed_at or "进行中",
r.duration_hours,
r.latest_valid_remark or "",
])
data = output.getvalue().encode("utf-8-sig") # 带 BOM,Excel 正确识别中文
buf = io.BytesIO(data)
buf.seek(0)
return StreamingResponse(
buf,
media_type="text/csv; charset=utf-8",
headers={"Content-Disposition": "attachment; filename=people_history.csv"},
)
@router.get("/messages", response_model=ProductMessageList)
async def dashboard_messages(
keyword: str = Query("", description="搜索: SN码/物料名/留言人/内容"),
skip: int = Query(0, ge=0),
limit: int = Query(30, ge=1, le=200),
db: AsyncSession = Depends(get_db),
):
"""
协同留言搜索(上帝视角 — 全厂所有产品留言)。
关联 Product 表返回 serial_number + material_name,
按时间倒序排列。
"""
return await search_product_messages(db, keyword=keyword, skip=skip, limit=limit)