unis-oa/backend/app/api/export.py

407 lines
18 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

"""列表导出:把「当前筛选条件」下的数据导成 CSV。
只做读路径,不碰流转。查询条件与列表接口逐字复用同一套函数
(``_created_query`` / ``_task_filter`` / ``_admin_work_page`` / ``_admin_task_stmt``),
所以界面上看不到的单子一定导不出来,不会出现「列表里没有、导出却有」的越权。
三件值得一提的事:
- 编码带 UTF-8 BOM:Excel 双击打开中文不乱码,这是导出现场最常见的坑。
- 表单字段摊不摊成列,取决于本次导出的数据是不是同一张表单。同一张才摊开,
混在一起摊会多出几十列空值,反而不如固定列好读。
- 字典值一律翻成标签再落地,导出来的是「差旅费」而不是「CL01」。
"""
from __future__ import annotations
import csv
import io
from datetime import datetime
from urllib.parse import quote
from fastapi import APIRouter, Depends, Query, Response
from sqlalchemy import select
from sqlalchemy.orm import Session
from .. import models
from ..db import get_db
from ..deps import CurrentUser, current_user
from ..envelope import forbidden
from ..service import completed as completed_service
from ..service import dicts as dicts_service
from ..service import formruntime
from .runtime import _admin_task_stmt, _admin_work_page, _created_query, _task_conditions, _task_filter
router = APIRouter(tags=["export"])
#: 工作状态下拉框里的取值 -> 中文标签,与前端 utils/oa.ts 的口径一致。
WORK_STATUS_LABELS = {
"running": "在途",
"completed": "办结",
"terminated": "终止",
"canceled": "作废",
"pending": "待处理",
}
#: 一次导出的行数上限。列表接口每页最多 200,导出是给整月报表用的,
#: 但不能没有上限:一张宽表单导出几万行会把浏览器和数据库连接一起拖垮。
EXPORT_LIMIT = 5000
WORK_COLUMNS = ("单号", "标题", "流程", "分类", "状态", "发起人", "发起部门", "发起时间", "办结时间",
"耗时", "当前环节", "当前处理人")
TASK_COLUMNS = ("单号", "标题", "流程", "分类", "环节", "处理人", "处理人部门", "发起人",
"到达时间", "完成时间", "处理动作", "处理意见", "是否超期")
# ---------------------------------------------------------------------------
# 值 -> 单元格文本
# ---------------------------------------------------------------------------
def _dt(value: datetime | None) -> str:
return "" if value is None else value.replace(microsecond=0).isoformat(sep=" ")
def _status_label(value: object, paused: bool = False) -> str:
key = str(value or "")
label = WORK_STATUS_LABELS.get(key, key)
# 挂起不改流程状态,导出的 CSV 里就得靠这一眼看出来:筛完「只看挂起」导出去,
# 状态列如果还只写「运行中」,这张表等于把干预动作全抹掉了。
return f"{label}(已挂起)" if paused and key == "running" else label
def _duration_text(seconds: object) -> str:
try:
total = int(seconds or 0) # type: ignore[arg-type]
except (TypeError, ValueError):
return ""
if total <= 0:
return ""
days, rest = divmod(total, 86400)
hours, rest = divmod(rest, 3600)
minutes = rest // 60
parts = []
if days:
parts.append(f"{days}天")
if hours:
parts.append(f"{hours}小时")
if minutes or not parts:
parts.append(f"{minutes}分")
return "".join(parts)
def _scalar_text(value: object) -> str:
if value is None:
return ""
if isinstance(value, bool):
return "是" if value else "否"
if isinstance(value, (list, tuple, set)):
return "、".join(str(item) for item in value if str(item or "").strip() != "")
if isinstance(value, dict):
return ";".join(f"{key}={_scalar_text(item)}" for key, item in value.items())
return str(value)
def cell_text(
field: dict, value: object, cache: dicts_service.DictCache, jobs: dict[str, str] | None = None
) -> str:
"""单个表单字段落地成什么文本:选项翻标签,明细表压一行,附件只留文件名。"""
kind = str(field.get("type") or "")
if value is None or (isinstance(value, str) and not value.strip()):
return ""
if kind == "signature":
# 签名是几十 KB 的 base64,导进表格既打不开也没意义,只留"签没签"这个事实。
return "已签名" if str(value).strip() else ""
if kind in ("relation", "picker"):
if dicts_service.source_kind_of(field) != dicts_service.SOURCE_PROCESS:
# 这一格关联的是字典项或外部数据源的编码,不是单据 job:
# 拿单据名册去翻只会原样吐回一串看不懂的主键,按候选来源翻才念得人话。
return dicts_service.option_labels(field, value, cache)
names = jobs or {}
labels = [names.get(str(item), str(item)) for item in _relation_ids(value)]
return "、".join(label for label in labels if label)
if kind == "table":
return _table_text(field, value, cache, jobs)
if kind in ("select", "radio", "checkbox"):
return dicts_service.option_labels(field, value, cache)
if kind == formruntime.CASCADER_TYPE:
# 级联的值是一条自上而下的路径,用斜杠分开才看得出是"华东 / 上海"而不是两个并列选项。
return dicts_service.option_labels(field, value, cache, sep=" / ")
if kind == "switch":
return "是" if value in (True, "true", 1, "1") else "否"
if kind in ("attachment", "image"):
names = [str(item.get("name") or "") for item in formruntime.rows_of(value)]
return "、".join(name for name in names if name) or _scalar_text(value)
if kind in ("daterange", "timerange"):
# 区间那两项念成"起 ~ 止",直接转字符串会把中括号和引号一起灌进单元格
text = formruntime.range_text(value)
if text:
return text
if kind == "week":
return formruntime.week_text(value)
if kind == "months":
# 多选月份存的是 YYYY-MM 数组,念成"2026年10-11月"才像一句人话
return formruntime.months_text(value)
if kind == formruntime.LOCATION_TYPE:
return formruntime.location_text(value)
if kind == "richtext":
# 存的是 Markdown 原文:去掉记号再进表格,否则一格里躺着的是 ## 和 - 而不是话
return formruntime.markdown_text(value)
if kind == "money" and field.get("uppercase"):
upper = formruntime.chinese_upper(value)
return f"{_scalar_text(value)}({upper})" if upper else _scalar_text(value)
return _scalar_text(value)
def _relation_ids(value: object) -> list[str]:
"""关联审批单的值收成 job 列表:单个字符串、对象数组、字符串数组都认。"""
if isinstance(value, str):
return [value] if value.strip() else []
if isinstance(value, dict):
return [str(value.get("job") or "")] if value.get("job") else []
if isinstance(value, (list, tuple)):
out: list[str] = []
for item in value:
out.extend(_relation_ids(item))
return out
return []
def _table_text(
field: dict, value: object, cache: dicts_service.DictCache, jobs: dict[str, str] | None = None
) -> str:
"""明细表压成一格:``姓名=张三;金额=500 | 姓名=李四;金额=800``。"""
columns = formruntime.columns_of(field)
lines: list[str] = []
for row in formruntime.rows_of(value):
pieces: list[str] = []
if columns:
for column in columns:
key = str(column.get("key") or "")
text = cell_text(column, row.get(key), cache, jobs)
if text:
pieces.append(f"{column.get('label') or key}={text}")
else:
pieces = [f"{key}={_scalar_text(item)}" for key, item in row.items()]
if pieces:
lines.append(";".join(pieces))
return " | ".join(lines)
# ---------------------------------------------------------------------------
# 查询与列拼装
# ---------------------------------------------------------------------------
def form_export_fields(db: Session, form_id: str) -> list[dict]:
"""这张表单要摊成列的字段:有字段名、且真的参与录入。"""
row = db.get(models.FormElement, form_id) if form_id else None
return [
item
for item in formruntime.fields_of(row.content if row else {})
if str(item.get("key") or "") and formruntime.fillable(item)
]
def _work_lines(rows: list, db: Session, cache: dicts_service.DictCache, with_form: bool):
"""返回 (表头, 数据行)。只有一张表单时才追加表单字段列。"""
form_ids = {str(row.form or "") for row in rows if getattr(row, "form", "")}
fields = form_export_fields(db, next(iter(form_ids))) if (with_form and len(form_ids) == 1) else []
jobs = _job_names(db, rows, fields)
headers = list(WORK_COLUMNS) + [str(item.get("label") or item.get("key")) for item in fields]
lines: list[list[str]] = []
for row in rows:
data = dict(row.data or {})
line = [
str(row.serial or ""),
str(row.title or ""),
str(row.process_name or ""),
str(row.category_name or ""),
_status_label(row.status, bool(getattr(row, "paused", False))),
str(row.creator_person or ""),
str(row.creator_unit_name or ""),
_dt(getattr(row, "start_time", None)),
_dt(getattr(row, "finish_time", None)),
_duration_text(getattr(row, "duration", 0)),
str(row.current_activity_names or ""),
str(getattr(row, "manual_identity_text", "") or ""),
]
line.extend(
cell_text(field, data.get(str(field.get("key") or "")), cache, jobs) for field in fields
)
lines.append(line)
return headers, lines
def _job_names(db: Session, rows: list, fields: list[dict]) -> dict[str, str]:
"""把关联字段里出现的 job 一次性翻成「单号 标题」,避免逐行查库。"""
wanted: list[str] = []
for row in rows:
data = dict(row.data or {})
for field in fields:
# 只有「候选来自流程单据」的那几格存的是 job,别的来源不用去单据表里翻
if str(field.get("type") or "") not in ("relation", "picker") \
or dicts_service.source_kind_of(field) != dicts_service.SOURCE_PROCESS:
continue
for job in _relation_ids(data.get(str(field.get("key") or ""))):
if job not in wanted:
wanted.append(job)
if not wanted:
return {}
names: dict[str, str] = {}
for model in (models.Work, models.WorkCompleted):
for row in db.execute(select(model).where(model.job.in_(wanted))).scalars().all():
names.setdefault(row.job, f"{row.serial or ''} {row.title}".strip())
return {job: names.get(job, job) for job in wanted}
def _task_lines(rows: list) -> list[list[str]]:
lines: list[list[str]] = []
for row in rows:
lines.append(
[
str(row.serial or ""),
str(row.title or ""),
str(row.process_name or ""),
str(row.category_name or ""),
str(row.activity_name or ""),
str(getattr(row, "identity_name", "") or ""),
str(getattr(row, "unit_name", "") or ""),
str(getattr(row, "creator_person", "") or ""),
_dt(getattr(row, "start_time", None)),
_dt(getattr(row, "completed_time", None)),
str(getattr(row, "route_name", "") or ""),
str(getattr(row, "opinion", "") or ""),
"是" if bool(getattr(row, "expired", False)) else "否",
]
)
return lines
def _csv(headers: list[str], rows: list[list[str]], filename: str) -> Response:
buffer = io.StringIO()
writer = csv.writer(buffer)
writer.writerow(headers)
writer.writerows(rows)
return Response(
content=("\ufeff" + buffer.getvalue()).encode("utf-8"),
media_type="text/csv; charset=utf-8",
headers={
# 中文文件名走 RFC 5987,另留一个 ASCII 兜底给老版 Excel 和 curl -O。
"Content-Disposition": f"attachment; filename=\"export.csv\"; filename*=UTF-8''{quote(filename)}",
"Cache-Control": "no-store",
},
)
# ---------------------------------------------------------------------------
# 接口
# ---------------------------------------------------------------------------
@router.get("/export/works")
def export_works(
scope: str = Query("created", description="created=我发起的 / admin=流程监控范围"),
keyword: str = Query(""),
process: str = Query(""),
status: str = Query(""),
start_date: str = Query(""),
end_date: str = Query(""),
expired: str = Query("", description="admin 范围用:1=只导手里压着超时候办的单子"),
paused: str = Query("", description="admin 范围用:1=只导被挂起的在途单;0=排除被挂起的"),
with_form: bool = Query(True, description="导出的是同一张表单时,是否把表单字段摊成列"),
db: Session = Depends(get_db),
user: CurrentUser = Depends(current_user),
) -> Response:
"""导出「我发起的」,或管理员监控范围内的流程单。"""
cache = dicts_service.DictCache(db)
if scope == "admin":
if not user.can("monitor:work"):
raise forbidden("无权限导出流程监控数据")
# 与监控列表同一个取数函数:界面上筛出来是哪些单子,导出来就是哪些单子,
# 在途的、办结的、终止的都在里面,不会出现「屏上有、CSV 里没有」。
rows, _total = _admin_work_page(
db,
user,
keyword=keyword,
process=process,
status=status,
start_date=start_date,
end_date=end_date,
expired=expired,
paused=paused,
limit=EXPORT_LIMIT,
)
else:
rows = []
if status in ("", "running"):
rows += _created_query(models.Work, user, keyword, process, status, start_date, end_date, db)
if status in ("", "completed", "terminated", "canceled"):
rows += _created_query(models.WorkCompleted, user, keyword, process, status, start_date, end_date, db)
rows.sort(key=lambda row: row.finish_time or row.start_time or row.create_time, reverse=True)
rows = rows[:EXPORT_LIMIT]
headers, lines = _work_lines(rows, db, cache, with_form)
return _csv(headers, lines, f"流程数据_{datetime.now():%Y%m%d_%H%M}.csv")
@router.get("/export/tasks")
def export_tasks(
scope: str = Query("processing", description="processing=我的待办 / completed=我的已办 / admin=流程监控的全部待办"),
keyword: str = Query(""),
process: str = Query(""),
category: str = Query(""),
expired: str = Query(""),
start_date: str = Query(""),
end_date: str = Query(""),
db: Session = Depends(get_db),
user: CurrentUser = Depends(current_user),
) -> Response:
"""导出待办 / 已办。
``processing`` 与 ``completed`` 的查询条件本身就锁死本人身份,不需要额外权限点;
``admin`` 是流程监控页「全部待办」那个页签用的,挂 ``monitor:work`` 并走同一套数据范围,
免得监控页看着一片、导出来却只有自己的几条。
已办那一档跟页面一样按单折叠(见 :mod:`app.service.completed`),别导出一张单
好几行——那份 CSV 十有八九是拿去数"这个月办了几张单"的。
"""
if scope == "admin":
if not user.can("monitor:work"):
raise forbidden("无权限导出流程监控数据")
stmt = _admin_task_stmt(
db,
user,
keyword=keyword,
process=process,
category=category,
expired=expired,
start_date=start_date,
end_date=end_date,
)
rows = list(db.execute(stmt.order_by(models.Task.start_time.desc()).limit(EXPORT_LIMIT)).scalars().all())
return _csv(list(TASK_COLUMNS), _task_lines(rows), f"监控待办_{datetime.now():%Y%m%d_%H%M}.csv")
if scope == "completed":
# 导出跟页面同一个口径:一张单只出一行。界面上合成一条、导出却摊成好几行,
# 拿 CSV 对账的人会以为自己少算了单,多出来的那一列「处理次数」把几次表态
# 的账留在同一行上,不靠他记住页面上看过的那个数。
groups = completed_service.collapse(
db,
_task_conditions(
models.TaskCompleted, user, keyword, process, category, "", "", start_date, end_date,
date_field="completed_time",
),
limit=EXPORT_LIMIT,
)
rows = [group.row for group in groups]
counts = {group.row.id: int(group.handles) for group in groups}
return _csv(
[*TASK_COLUMNS, "处理次数"],
[line + [str(counts.get(row.id, 1))] for line, row in zip(_task_lines(rows), rows)],
f"我的已办_{datetime.now():%Y%m%d_%H%M}.csv",
)
stmt = _task_filter(models.Task, user, keyword, process, category, "", expired, start_date, end_date)
rows = list(db.execute(stmt.order_by(models.Task.start_time.desc()).limit(EXPORT_LIMIT)).scalars().all())
return _csv(list(TASK_COLUMNS), _task_lines(rows), f"我的待办_{datetime.now():%Y%m%d_%H%M}.csv")