Files
zkxw/web-admin/src/utils/oa-approval-print.ts
T
zlwuandCursor b5c4ba4c4f feat(oa): format money fields in print and related-approval summary
Show formatted amount with optional uppercase on print; summary uses numeric text.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-30 11:11:13 +08:00

630 lines
19 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* OA 审批单钉钉风格 PDF 导出
* Spec: docs/superpowers/specs/2026-07-15-oa-approval-print-pdf-design.md
* Nested related: docs/superpowers/specs/2026-07-22-oa-related-approval-nested-print-design.md
*/
import { createApp, h, nextTick } from 'vue'
import html2canvas from 'html2canvas'
import { jsPDF } from 'jspdf'
import {
assembleRelatedPrintBlocks,
normalizeRelatedIdsFromFormValue,
type RelatedPrintBlock
} from '@/utils/oa-approval-print-related'
import { formatProgressPersonLines } from '@/utils/oa-progress-person-lines'
import { formatDeptDisplay } from '@/utils/oa-dept-value'
import { formatMoneyDisplay } from '@/utils/money-format'
import { toRmbUpper } from '@/utils/rmb-upper'
export const OA_PRINT_COMPANY_NAME = '安徽中科兴皖医学研究有限公司'
export type OaStampClass = 'ok' | 'run' | 'rej' | 'ret' | 'can'
export type { RelatedPrintBlock }
export type OaPrintFieldRow = {
label: string
/** 普通文本(可含换行) */
text?: string
/** 附件 / 链接列表 */
urls?: string[]
/** 关联审批单多行块(优先于 text) */
blocks?: RelatedPrintBlock[]
}
export type OaPrintFlowItem = {
left: string
right: string
/** @deprecated 多人节点改用 personLines;单人/发起人可保留 */
comment?: string
/** 或签/会签按人纯文本行 */
personLines?: string[]
}
export type OaPrintModel = {
title: string
companyName: string
createDate: string
stampClass: OaStampClass
stampText: string
rows: OaPrintFieldRow[]
flowItems: OaPrintFlowItem[]
printTime: string
printerName: string
watermarkName: string
}
const STATUS_TEXT: Record<string, string> = {
pending: '待处理',
running: '进行中',
approved: '已同意',
rejected: '已拒绝',
completed: '已完成',
cancelled: '已撤销',
done: '已结束',
submitted: '已提交',
not_reached: '未到达',
returned: '已打回',
transferred: '已转交'
}
const UPLOAD_TYPES = new Set([
'upload',
'fcUpload',
'elUpload',
'el-upload',
'attachment',
'file',
'files'
])
const SKIP_RULE_TYPES = new Set([
'div',
'fcRow',
'fcCol',
'fcTable',
'fcTableGrid',
'col',
'row',
'group',
'tab',
'tabs',
'space',
'divider',
'html',
'vanCellGroup'
])
export function resolveStamp(status: string | undefined | null): {
stampClass: OaStampClass
stampText: string
} {
const s = String(status || '').trim()
if (s === 'completed' || s === 'approved' || s === 'done') {
return { stampClass: 'ok', stampText: '已通过' }
}
if (s === 'rejected') return { stampClass: 'rej', stampText: '已拒绝' }
if (s === 'returned') return { stampClass: 'ret', stampText: '已打回' }
if (s === 'cancelled') return { stampClass: 'can', stampText: '已撤销' }
if (s === 'running' || s === 'pending') {
return { stampClass: 'run', stampText: '审批中' }
}
return { stampClass: 'run', stampText: '审批中' }
}
function statusText(s: string) {
return STATUS_TEXT[s] || s || '-'
}
function formatDateOnly(createTime: string | undefined | null): string {
const raw = String(createTime || '').trim()
if (!raw) return '-'
return raw.slice(0, 10)
}
function formatNow(): string {
const d = new Date()
const pad = (n: number) => String(n).padStart(2, '0')
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
}
function isHttpUrl(s: string) {
return /^https?:\/\//i.test(s)
}
function extractUrls(value: unknown): string[] {
if (value == null || value === '') return []
if (Array.isArray(value)) {
const out: string[] = []
for (const item of value) {
if (typeof item === 'string') {
const parts = item
.split(',')
.map((x) => x.trim())
.filter(Boolean)
out.push(...parts)
} else if (item && typeof item === 'object') {
const u = (item as any).url || (item as any).fileUrl || (item as any).path
if (u) out.push(String(u))
}
}
return out
}
if (typeof value === 'string') {
return value
.split(',')
.map((x) => x.trim())
.filter(Boolean)
}
if (typeof value === 'object') {
const u = (value as any).url || (value as any).fileUrl
return u ? [String(u)] : []
}
return []
}
function formatScalar(value: unknown, sep = '、'): string {
if (value == null || value === '') return '-'
if (typeof value === 'boolean') return value ? '是' : '否'
if (typeof value === 'number') return String(value)
if (typeof value === 'string') return value.trim() || '-'
if (Array.isArray(value)) {
if (!value.length) return '-'
return value
.map((v) => formatScalar(v))
.filter((s) => s && s !== '-')
.join(sep)
}
if (typeof value === 'object') {
try {
return JSON.stringify(value)
} catch {
return String(value)
}
}
return String(value)
}
/** 日期/时间区间(FormCreate:日期区间、时间区间等)打印用 ~ 连接起止 */
function isRangeFieldRule(rule: any): boolean {
const type = String(rule?.type || '').trim()
const props = rule?.props && typeof rule.props === 'object' ? rule.props : {}
if (type === 'datePicker' || type === 'date' || type === 'dateRange') {
return /range$/i.test(String(props.type || type))
}
if (type === 'timePicker' || type === 'time' || type === 'timeRange') {
return props.isRange === true || type === 'timeRange'
}
return false
}
function formatFieldValue(value: unknown, rule: any): string {
if (Array.isArray(value) && isRangeFieldRule(rule)) {
return formatScalar(value, '~')
}
return formatScalar(value)
}
async function walkRules(
rules: any[],
formData: Record<string, any>,
out: OaPrintFieldRow[]
) {
if (!Array.isArray(rules)) return
for (const rule of rules) {
if (!rule || typeof rule !== 'object') continue
const type = String(rule.type || '').trim()
const children = rule.children || rule.props?.rule
if (Array.isArray(children) && children.length) {
await walkRules(children, formData, out)
}
if (SKIP_RULE_TYPES.has(type)) continue
const field = String(rule.field || '').trim()
if (!field) continue
const label = String(rule.title || rule.label || rule.props?.label || field).trim() || field
const value = formData?.[field]
if (type === 'relatedApproval') {
const ids = normalizeRelatedIdsFromFormValue(value)
if (!ids.length) {
out.push({ label, text: '-' })
continue
}
const blocks = await assembleRelatedPrintBlocks(ids)
out.push({
label,
blocks: blocks.length
? blocks
: [{ indexLabel: '1', title: '关联信息加载失败' }]
})
continue
}
if (type === 'dept') {
const text = formatDeptDisplay(value)
out.push({ label, text: text || '-' })
continue
}
if (type === 'money') {
const showUpper = rule.props?.showUpper !== false
const n =
value == null || value === ''
? null
: typeof value === 'number'
? value
: Number(String(value).replace(/,/g, ''))
if (n == null || !Number.isFinite(n)) {
out.push({ label, text: '-' })
continue
}
const numText = formatMoneyDisplay(n, 2)
const upper = showUpper ? toRmbUpper(n) : ''
out.push({
label,
text: upper ? `${numText}(${upper})` : numText
})
continue
}
if (UPLOAD_TYPES.has(type) || String(rule.name || '').toLowerCase().includes('upload')) {
const urls = extractUrls(value)
out.push({ label, urls: urls.length ? urls : [], text: urls.length ? undefined : '-' })
continue
}
// 字符串里像 URL 列表的也拆开展示
if (typeof value === 'string' && value.includes('http') && value.includes(',')) {
const urls = extractUrls(value).filter(isHttpUrl)
if (urls.length >= 2) {
out.push({ label, urls })
continue
}
}
const urls = extractUrls(value).filter(isHttpUrl)
if (urls.length && (Array.isArray(value) || UPLOAD_TYPES.has(type))) {
out.push({ label, urls })
continue
}
out.push({ label, text: formatFieldValue(value, rule) })
}
}
async function buildFormRows(detail: any): Promise<OaPrintFieldRow[]> {
const schema = detail?.formSchemaJson
const formData = (detail?.formDataJson || {}) as Record<string, any>
const rule = Array.isArray(schema?.rule)
? schema.rule
: Array.isArray(schema)
? schema
: []
const out: OaPrintFieldRow[] = []
await walkRules(rule, formData, out)
if (out.length) return out
// schema 缺失:兜底平铺 formData
for (const [k, v] of Object.entries(formData)) {
const urls = extractUrls(v).filter(isHttpUrl)
if (urls.length) out.push({ label: k, urls })
else out.push({ label: k, text: formatScalar(v) })
}
return out
}
/** 钉钉风格:人名不加状态括号,状态放在整行末尾 */
function peopleDisplayNames(p: any): string[] {
const people = Array.isArray(p?.people) ? p.people : []
const fromPeople = people
.map((x: any) => String(x?.nickName || x?.id || '').trim())
.filter(Boolean)
if (fromPeople.length) return fromPeople
const name = String(p?.assigneeUserName || p?.assigneeUserId || '').trim()
return name ? [name] : []
}
function progressPersonLinesFromItem(p: any): string[] {
const people = Array.isArray(p?.people) ? p.people : []
if (!people.length) return []
return formatProgressPersonLines(people).map((x) => x.text)
}
function isCcProgressItem(p: any): boolean {
const taskType = String(p?.taskType || p?.task_type || '').trim()
const signMode = String(p?.signMode || p?.sign_mode || '').trim()
const title = String(p?.title || p?.nodeName || '').trim()
// 主判据:taskType / signMode;标题兜底仅匹配默认「抄送人」或「抄送…」节点名
return (
taskType === 'cc' ||
signMode === 'cc' ||
title === '抄送人' ||
/^抄送/.test(title)
)
}
/**
* 从 progress 组装审批流程行;抄送节点聚合为「抄送A, B, C」对齐钉钉导出。
* 若 progress 漏抄送,则用 tasks 兜底补一行。
*/
export function buildFlowItems(detail: any): OaPrintFlowItem[] {
const list = Array.isArray(detail?.progress) ? detail.progress : []
const items: OaPrintFlowItem[] = []
// 聚合连续抄送任务,对齐钉钉「抄送A, B, C」
let ccBuf: { names: string[]; ts: string } | null = null
const flushCc = () => {
if (!ccBuf) return
const uniq = Array.from(new Set(ccBuf.names.map((n) => n.trim()).filter(Boolean)))
items.push({
left: uniq.length ? `抄送: ${uniq.join(', ')}` : '抄送:',
right: ccBuf.ts || ''
})
ccBuf = null
}
for (const p of list) {
const kind = String(p.kind || '')
const title = String(p.title || '-').trim()
const names = peopleDisplayNames(p)
const name = names.join(', ')
const ts = String(p.timestamp || '').trim()
const comment = String(p.commentText || '').trim()
const st = statusText(String(p.status || ''))
const signMode = String(p.signMode || p.sign_mode || '')
const signLabel = signMode === 'and' ? '会签' : signMode === 'or' ? '或签' : ''
if (isCcProgressItem(p)) {
if (!ccBuf) ccBuf = { names: [], ts }
if (names.length) ccBuf.names.push(...names)
if (ts) ccBuf.ts = ts
continue
}
flushCc()
if (kind === 'submit') {
items.push({
left: name ? `【${title}】 ${name} ${st}` : `【${title}】 ${st}`,
right: ts,
comment: comment || undefined
})
continue
}
if (kind === 'terminal') {
// 打回结果已落在审批人节点,不单独输出终态「已打回」行
if (String(p.status || '') === 'returned' || title === '已打回') {
continue
}
items.push({
left: title || st,
right: ts
})
continue
}
if (kind === 'pending_node') {
const personLines = progressPersonLinesFromItem(p)
const head = signLabel ? `【${title}·${signLabel}】` : `【${title}】`
items.push({
left: personLines.length
? `${head} ${st}`
: name
? `${head} ${name} ${st}`
: `${head} ${st}`,
right: personLines.length ? '' : ts,
personLines: personLines.length ? personLines : undefined
})
continue
}
// task(或签/会签同节点多人已合并)
const head = signLabel ? `【${title}·${signLabel}】` : `【${title}】`
const personLines = progressPersonLinesFromItem(p)
if (personLines.length) {
items.push({
left: `${head} ${st}`,
right: '',
personLines
})
continue
}
items.push({
left: name ? `${head} ${name} ${st}` : `${head} ${st}`,
right: ts,
comment: comment || undefined
})
}
flushCc()
// progress 未带抄送时,用 tasks 兜底(对齐钉钉:流程末展示抄送人)
const hasCcLine = items.some((it) => it.left.startsWith('抄送'))
if (!hasCcLine) {
const tasks = Array.isArray(detail?.tasks) ? detail.tasks : []
const ccTasks = tasks.filter((t: any) => {
const tt = String(t?.taskType || t?.task_type || '').trim()
const sm = String(t?.signMode || t?.sign_mode || '').trim()
return tt === 'cc' || sm === 'cc'
})
if (ccTasks.length) {
const names = ccTasks
.map((t: any) =>
String(t?.assigneeUserName || t?.assignee_user_name || t?.assigneeUserId || '').trim()
)
.filter(Boolean)
const uniq = Array.from(new Set(names))
let ts = ''
for (const t of ccTasks) {
const tTs = String(t?.updateTime || t?.createTime || '').trim()
if (tTs && (!ts || tTs > ts)) ts = tTs
}
if (uniq.length) {
items.push({ left: `抄送: ${uniq.join(', ')}`, right: ts })
}
}
}
return items
}
export async function buildOaPrintModel(
detail: any,
opts: { printerName: string; printTime?: string }
): Promise<OaPrintModel> {
const { stampClass, stampText } = resolveStamp(detail?.status)
const appName = String(detail?.appName || '').trim()
const titleFallback = String(detail?.title || '').trim()
const title = appName || titleFallback || '审批单'
const printerName = String(opts.printerName || '').trim() || '-'
const printTime = opts.printTime || formatNow()
const headerRows: OaPrintFieldRow[] = [
{ label: '审批编号', text: String(detail?.id || '-').trim() || '-' },
{
label: '创建人',
text: String(detail?.initiatorUserName || detail?.initiatorUserId || '-').trim() || '-'
},
{
label: '创建人部门',
text:
String(detail?.initiatorDeptName || detail?.initiatorDept || '-').trim() || '-'
}
]
const formRows = await buildFormRows(detail)
return {
title,
companyName: OA_PRINT_COMPANY_NAME,
createDate: formatDateOnly(detail?.createTime),
stampClass,
stampText,
rows: [...headerRows, ...formRows],
flowItems: buildFlowItems(detail),
printTime,
printerName,
watermarkName: printerName === '-' ? '审批' : printerName
}
}
export function buildOaPrintFilename(detail: any): string {
const initiator =
String(detail?.initiatorUserName || '').trim() ||
String(detail?.initiatorUserId || '').trim() ||
'用户'
const appName =
String(detail?.appName || '').trim() ||
String(detail?.title || '').trim() ||
'审批单'
const safe = (s: string) => s.replace(/[\\/:*?"<>|]/g, '_').slice(0, 80)
return `${safe(initiator)}提交的${safe(appName)}.pdf`
}
/** 用 canvas 绘制中文页码(jsPDF 内置字体不支持汉字,会乱码) */
function renderPageLabelCanvas(text: string): HTMLCanvasElement {
const font = '20px "PingFang SC", "Microsoft YaHei", "Heiti SC", sans-serif'
const measure = document.createElement('canvas')
const mctx = measure.getContext('2d')
if (!mctx) {
const empty = document.createElement('canvas')
empty.width = 1
empty.height = 1
return empty
}
mctx.font = font
const tw = Math.ceil(mctx.measureText(text).width) + 8
const th = 28
const scale = 2
const c = document.createElement('canvas')
c.width = tw * scale
c.height = th * scale
const ctx = c.getContext('2d')
if (!ctx) return c
ctx.scale(scale, scale)
ctx.clearRect(0, 0, tw, th)
ctx.font = font
ctx.fillStyle = '#646464'
ctx.textBaseline = 'middle'
ctx.fillText(text, 4, th / 2)
return c
}
async function canvasToPdf(canvas: HTMLCanvasElement, filename: string) {
const pdf = new jsPDF({ orientation: 'p', unit: 'mm', format: 'a4' })
const pageWidth = pdf.internal.pageSize.getWidth()
const pageHeight = pdf.internal.pageSize.getHeight()
const imgWidth = pageWidth
const imgHeight = (canvas.height * imgWidth) / canvas.width
// 略超一页(原 min-height / 浮点)时不产生空白尾页;余量 < 1.5mm 仍算一页
const EPS_MM = 1.5
const totalPages = Math.min(40, Math.max(1, Math.ceil((imgHeight - EPS_MM) / pageHeight)))
const pageData = canvas.toDataURL('image/jpeg', 0.95)
const labelMmH = 4.5
for (let pageIndex = 0; pageIndex < totalPages; pageIndex++) {
if (pageIndex > 0) pdf.addPage()
const position = -pageIndex * pageHeight
pdf.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)
const label = `第${pageIndex + 1}页`
const labelCanvas = renderPageLabelCanvas(label)
if (labelCanvas.width > 1) {
const labelMmW = (labelCanvas.width / labelCanvas.height) * labelMmH
pdf.addImage(
labelCanvas.toDataURL('image/png'),
'PNG',
(pageWidth - labelMmW) / 2,
pageHeight - 10,
labelMmW,
labelMmH
)
}
}
pdf.save(filename)
}
/**
* 根据实例详情导出 PDF(不弹系统打印框)
*/
export async function exportOaApprovalPdf(
detail: any,
opts: { printerName: string }
): Promise<void> {
const model = await buildOaPrintModel(detail, { printerName: opts.printerName })
const filename = buildOaPrintFilename(detail)
const { default: OaApprovalPrintSheet } = await import(
'@/components/oa-approval/OaApprovalPrintSheet.vue'
)
const host = document.createElement('div')
host.setAttribute('data-oa-print-host', '1')
host.style.cssText =
'position:fixed;left:-100000px;top:0;width:794px;z-index:-1;opacity:1;pointer-events:none;'
document.body.appendChild(host)
const app = createApp({
render: () => h(OaApprovalPrintSheet, { model })
})
app.mount(host)
try {
await nextTick()
// 给浏览器一帧完成布局 / 字体
await new Promise((r) => requestAnimationFrame(() => r(undefined)))
await new Promise((r) => setTimeout(r, 50))
const el = host.querySelector('.oa-print-page') as HTMLElement | null
if (!el) throw new Error('print sheet missing')
const canvas = await html2canvas(el, {
scale: 2,
useCORS: true,
allowTaint: true,
backgroundColor: '#ffffff',
logging: false,
windowWidth: el.scrollWidth,
windowHeight: el.scrollHeight
})
await canvasToPdf(canvas, filename)
} finally {
app.unmount()
host.remove()
}
}