unis-oa/backend/app/service/exportfmt.py

230 lines
9.8 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.

"""导出单元格的取值口径:一个字段值该落成什么样的文本。
从 ``api/export.py`` 原样搬过来的这一层是**纯值渲染**,两条导出口都用它
(``api/export.py`` 的列表导出、``service/detail_export.py`` 的流程明细导出),
所以搬成了独立模块——同一个字段在两张导出表里必须长一个样。
搬过来时把下划线开头的名字放开了,因为它不再是某个模块的私货;
``api/export.py`` 按老名字 re-import 回来,那边的调用与既有文档引用都不动。
三条值得一提的口径(原文照抄,别在这儿漂):
- 字典值一律翻成标签再落地,导出来的是「差旅费」而不是「CL01」。
- 签名是几十 KB 的 base64,只留「签没签」这个事实;附件只留文件名。
- 明细表压成一格 ``姓名=张三;金额=500 | 姓名=李四;金额=800``。
"""
from __future__ import annotations
from datetime import datetime
from typing import TYPE_CHECKING
from sqlalchemy import select
from .. import models
from . import dicts as dicts_service
from . import formruntime
if TYPE_CHECKING:
from sqlalchemy.orm import Session
# ---------------------------------------------------------------------------
# 状态标签
# ---------------------------------------------------------------------------
#: 工作状态下拉框里的取值 -> 中文标签,与前端 utils/oa.ts 的口径一致。
WORK_STATUS_LABELS = {
"running": "在途",
"completed": "办结",
"terminated": "终止",
"canceled": "作废",
"pending": "待处理",
}
# ---------------------------------------------------------------------------
# 值 -> 单元格文本
# ---------------------------------------------------------------------------
# ---------------------------------------------------------------------------
# 值 -> 单元格文本
# ---------------------------------------------------------------------------
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,
data: dict | None = None,
) -> str:
"""单个表单字段落地成什么文本:选项翻标签,明细表压一行,附件只留文件名。
带上这一单的值(``data``)时,挂了候选路由的格子先换成**这一单命中的那一条**再翻名字,
与界面渲染、提交把关同一个口径;不给就按字段自己那一份,老调用方一个都不用改。
"""
if value is None or (isinstance(value, str) and not value.strip()):
return ""
if data is not None:
field = dicts_service.option_view(field, data)
kind = str(field.get("type") or "")
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 "")
# 列上的路由读的是同一行里别的列(与桌面 FormRenderer 那一格同一个口径)
text = cell_text(column, row.get(key), cache, jobs, data=row)
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)
]
# ---------------------------------------------------------------------------
# 关联审批单:job -> 「单号 标题」
# ---------------------------------------------------------------------------
def relation_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}