Align asset columns in disposal notices

This commit is contained in:
WuYongJie 2026-11-10 18:41:42 +08:00
parent 943196bbc0
commit 2d83bc8b4d
3 changed files with 140 additions and 40 deletions

View File

@ -45,10 +45,16 @@ test('批量报废在本机隔离 MySQL 验证完整资产树、事务和审批
auto_return_token?: string;
confirmed_quantities?: { equipment_id: number; total_quantity: number }[] }[], ip?: string) => call(createBatchDisposal,
{ assets, disposal_reason: '设备老化', disposal_method: '报废', notes: '本机验证' }, ip)
const assetLines = (content: string) => content.split('\n')
.filter(line => line.startsWith('- ')).map(line => line.slice(2).replace(/\\(.)/g, '$1'))
const assetLines = (content: string) => {
const paragraphs = content.split('\n\n')
const heading = paragraphs.findIndex(line => line.split(/[\u2002\u2009\u200a\u3000]+/).join(' ') === '**编码** **资产** **部门** **领用人**')
assert.ok(heading >= 0)
return paragraphs.slice(heading + 1).map(line => line.trim().replace(/[\u2002\u2009\u200a\u3000]+/g, ' · ').replace(/\\(.)/g, '$1'))
}
const codes = Array.from({ length: 335 }, (_, index) => data(`list-${String(index).padStart(3, '0')}`))
const codes = Array.from({ length: 335 }, (_, index) => ({
...data(`list-${String(index).padStart(3, '0')}`), equipment_name: index ? `资产${index}` : '主机'
}))
await prisma.equipment.createMany({ data: codes })
const roots = await prisma.equipment.findMany({ where: { equipment_code: { in: codes.map(row => row.equipment_code) } }, orderBy: { equipment_code: 'asc' } })
const root = roots[0]
@ -158,14 +164,19 @@ test('批量报废在本机隔离 MySQL 验证完整资产树、事务和审批
assert.ok(delivery.idempotency_key.length <= 160)
const payload = JSON.parse(delivery.payload_json)
assert.equal(payload.action_title, '查看待审批')
assert.equal(payload.message_version, index ? `rows-v2.part-${index + 1}` : 'rows-v2')
assert.match(payload.content, /\*\*待审批:\*\* 335 笔\n\n- /)
assert.equal(payload.message_version, index ? `columns-v3.part-${index + 1}` : 'columns-v3')
assert.match(payload.content, /\*\*待审批:\*\* 335 笔\n\n\*\*编码\*\*/)
assert.ok(payload.content.includes(`第 ${index + 1}/${deliveries.length} 部分`))
assert.ok(`### ${'题'.repeat(120)}\n\n${payload.content}`.length <= 4800)
return payload.content as string
})
assert.deepEqual(cards.flatMap(assetLines), roots.map((row, index) =>
`${row.equipment_code} · ${row.equipment_name}${index ? '' : '(含 2 项配件)'} · 未归属部门 · 未领用`))
assert.deepEqual(cards.flatMap(card => {
const lines = assetLines(card)
assert.equal(lines.length % 2, 0)
return lines
}), roots.flatMap((row, index) => [
row.equipment_code, `${row.equipment_name}${index ? '' : '+2配件'} · 未归属部门 · 未领用`
]))
const repeated = await submit([{ equipment_id: root.id, item_ids: [root.id, child.id, nested.id] }])
assert.equal(repeated.status, 409)
})
@ -183,19 +194,20 @@ test('批量报废在本机隔离 MySQL 验证完整资产树、事务和审批
const pendingNotices = () => prisma.notification.count({ where: { type: 'disposal', metadata: { contains: prefix } } })
await t.test('只归还明确选中的借用,配件、原库位及报废申请在同一事务处理', async () => {
const department = await prisma.department.create({ data: { name: prefix, source_system: 'ding_hr_business' } })
const department = await prisma.department.create({ data: { name: '测试部门', source_system: 'ding_hr_business' } })
departmentIds.push(department.id)
await prisma.person.update({ where: { id: person.id }, data: { main_department_id: department.id } })
const location = await prisma.storageLocation.create({ data: { name: prefix } })
storageIds.push(location.id)
const checkedOut = await prisma.equipment.create({ data: { ...data('auto-root'), storage_location_id: location.id } })
const checkedOut = await prisma.equipment.create({ data: { ...data('auto-root'), equipment_name: '主机', storage_location_id: location.id } })
const accessory = await prisma.equipment.create({ data: { ...data('auto-part', checkedOut.id), storage_location_id: location.id } })
const another = await prisma.equipment.create({ data: data('auto-another') })
const another = await prisma.equipment.create({ data: { ...data('auto-another'), equipment_name: '打印机-激光' } })
const unselected = await prisma.equipment.create({ data: data('auto-unselected') })
const ready = await prisma.equipment.create({ data: { ...data('auto-ready'), department_id: department.id } })
const ready = await prisma.equipment.create({ data: { ...data('auto-ready'), equipment_name: '库存设备', department_id: department.id } })
await prisma.borrowRecord.create({ data: { equipment_id: ready.id, equipment_code: ready.equipment_code,
person_id: person.id, person_name: '旧姓名', person_nickname: '旧领用人', status: '已归还', return_time: new Date() } })
const borrowedId = await borrow(checkedOut.id)
await prisma.borrowRecord.update({ where: { id: borrowedId }, data: { person_nickname: '现领用人' } })
const anotherBorrowId = await borrow(another.id)
await prisma.borrowRecord.update({ where: { id: anotherBorrowId }, data: { person_nickname: '', person_name: '实际姓名' } })
const unselectedBorrowId = await borrow(unselected.id)
@ -244,9 +256,9 @@ test('批量报废在本机隔离 MySQL 验证完整资产树、事务和审批
business_id: ids[0], recipient_user_id: reviewer.id } })
const payload = JSON.parse(delivery.payload_json)
assert.deepEqual(assetLines(payload.content), [
`${checkedOut.equipment_code} · ${checkedOut.equipment_name}(含 1 项配件) · ${department.name} · ${person.nickname}`,
`${ready.equipment_code} · ${ready.equipment_name} · ${department.name} · 未领用`,
`${another.equipment_code} · ${another.equipment_name} · ${department.name} · 实际姓名`
checkedOut.equipment_code, `${checkedOut.equipment_name}+1配件 · ${department.name} · 现领用人`,
ready.equipment_code, `${ready.equipment_name} · ${department.name} · 未领用`,
another.equipment_code, `${another.equipment_name} · ${department.name} · 实际姓名`
])
assert.equal(await prisma.disposalRecord.count({ where: { id: { in: ids }, status: 'pending' } }), 3)
assert.equal(await pendingNotices(), noticeCount + 1)

View File

@ -16,21 +16,52 @@ import {
const now = new Date('2026-07-14T03:00:00.000Z')
test('批量报废待审批的一张钉钉卡完整列出 12 项,并转义实际名称及部门', () => {
const assets = Array.from({ length: 12 }, (_, index) => ({
code: `PC-${index + 1}`, name: `设备[${index + 1}]`,
department: index === 0 ? '设计#组' : undefined,
holder: index === 0 ? '小_白' : undefined,
accessoryCount: index === 0 ? 2 : 0
}))
const [first, ...rest] = buildBatchDisposalAppliedDingTalkContents({ appliedAt: now, applicantName: '张三', reason: '故障', assets })
assert.equal(rest.length, 0)
assert.match(first, /\*\*待审批:\*\* 12 笔\n\n- /)
const lines = first.split('\n').filter(line => line.startsWith('- '))
assert.equal(lines.length, 12)
assert.equal(lines[0], String.raw`- PC\-1 · 设备\[1\](含 2 项配件) · 设计\#组 · 小\_白`)
assert.equal(lines[11], String.raw`- PC\-12 · 设备\[12\] · 未归属部门 · 未领用`)
assert.doesNotMatch(first, /请逐笔核对|第 1\/1 部分/)
test('批量报废钉钉卡将 11 或 12 项常见资产逐行对齐,并转义字段', () => {
const columnSpace = /[\u2002\u2009\u200a\u3000]+/
for (const count of [11, 12]) {
const assets = Array.from({ length: count }, (_, index) => ({
code: `JS-CPU-${String(index + 1).padStart(4, '0')}`,
name: index === 0 ? '主机' : '打印机-激光',
department: index === 0 ? '设计#组' : undefined,
holder: index === 0 ? '小_白' : undefined,
accessoryCount: index === 0 ? 2 : 0
}))
const [first, ...rest] = buildBatchDisposalAppliedDingTalkContents({ appliedAt: now, applicantName: '张三', reason: '故障', assets })
assert.equal(rest.length, 0)
const paragraphs = first.split('\n\n')
assert.equal(paragraphs[3], `**待审批:** ${count} 笔`)
assert.equal(paragraphs[4].split(columnSpace).join(' '), '**编码** **资产** **部门** **领用人**')
const lines = paragraphs.slice(5)
assert.equal(lines.length, count)
assert.deepEqual(lines[0].split(columnSpace), [
String.raw`JS\-CPU\-0001`, String.raw`主机\+2配件`, String.raw`设计\#组`, String.raw`小\_白`
])
assert.deepEqual(lines[count - 1].split(columnSpace), [
String.raw`JS\-CPU\-` + String(count).padStart(4, '0'), String.raw`打印机\-激光`, '未归属部门', '未领用'
])
assert.ok(lines[0].startsWith(String.raw`JS\-CPU\-0001` + '\u2009主机'))
assert.doesNotMatch(first, /请逐笔核对|第 1\/1 部分/)
}
})
test('长资产编码完整保留,名称、部门和领用人分别按列续行', () => {
const code = 'JS-CUSTOM-ABCDEFGHIJK-0001'
const [content] = buildBatchDisposalAppliedDingTalkContents({
appliedAt: now, applicantName: '张三', reason: '故障', assets: [{
code, name: '超长名称连续测试甲乙丙丁', department: '真实使用部门甲乙丙丁',
holder: '负责同事甲乙丙丁', accessoryCount: 0
}]
})
const lines = content.split('\n\n').slice(5)
assert.equal(lines.length, 4)
assert.equal(lines[0].replace(/\\(.)/g, '$1'), code)
const emptyCode = '\u3000'.repeat(6) + '\u2009\u2009'
assert.ok(lines.slice(1).every(line => line.startsWith(emptyCode)))
assert.deepEqual(lines.slice(1).map(line => line.slice(emptyCode.length).split(/[\u2002\u2009\u200a\u3000]+/)), [
['超长名称连', '真实使用部', '负责同事'],
['续测试甲乙', '门甲乙丙丁', '甲乙丙丁'],
['丙丁']
])
})
const rootEquipment = {

View File

@ -12,6 +12,7 @@ import {
MAX_DISPOSAL_BATCH_ROOTS, type DisposalTreeItem
} from '../utils/disposalSubmission'
import {
compactNotificationText,
createBusinessNotification,
escapeNotificationMarkdownInline,
findActiveDingTalkUsersByIds,
@ -164,6 +165,54 @@ export const buildDisposalAppliedDingTalkContent = (input: {
// The notification center reserves up to 120 characters for the visible title.
const BATCH_DISPOSAL_DINGTALK_BODY_LIMIT = 4800 - 120 - '### \n\n'.length
// Approximate the proportional card font in twentieths of an em.
const DISPOSAL_NOTICE_COLUMN_WIDTHS = [124, 110, 100, 80]
const noticeCharacterWidth = (character: string) => {
if (/\p{Mark}/u.test(character)) return 0
if (/[\p{Script=Han}\p{Script=Hangul}\p{Script=Hiragana}\p{Script=Katakana}\p{Extended_Pictographic}\u3000-\u303f\uff01-\uff60\uffe0-\uffe6]/u.test(character)) return 20
if (/[0-9]/.test(character)) return 11
if (/[A-Z]/.test(character)) return 13
if (character === '-') return 7
if (character === '+') return 12
if (/[ .,:;!'|]/.test(character)) return 5
return 10
}
const noticeTextWidth = (text: string) => Array.from(text).reduce((width, character) => width + noticeCharacterWidth(character), 0)
const wrapNoticeColumn = (text: string, limit: number) => {
const lines: string[] = []
let line = ''
let width = 0
for (const character of text) {
const characterWidth = noticeCharacterWidth(character)
if (width + characterWidth > limit) {
lines.push(line.trim())
line = ''
width = 0
}
line += character
width += characterWidth
}
lines.push(line.trim())
return lines
}
const noticeColumnPadding = (width: number) => {
const whole = '\u3000'.repeat(Math.floor(width / 20))
const half = '\u2002'.repeat(Math.floor(width % 20 / 10))
const thin = '\u2009'.repeat(Math.floor(width % 10 / 4))
const hair = '\u200a'.repeat(Math.floor(width % 10 % 4 / 2))
return whole + half + thin + hair
}
const renderNoticeColumns = (columns: string[], heading = false) => columns.map((column, index) => {
const escaped = column ? escapeNotificationMarkdownInline(column) : ''
const text = heading ? `**${escaped}**` : escaped
if (index === columns.length - 1) return text
return text + noticeColumnPadding(DISPOSAL_NOTICE_COLUMN_WIDTHS[index] - noticeTextWidth(column))
}).join('\u2009').trimEnd()
export const buildBatchDisposalAppliedDingTalkContents = (input: {
appliedAt: Date
@ -183,18 +232,26 @@ export const buildBatchDisposalAppliedDingTalkContents = (input: {
`**报废原因:** ${escapeNotificationMarkdownInline(input.reason, '未填写', 300)}`
]
const rows = input.assets.map(asset => {
const accessories = asset.accessoryCount ? `(含 ${asset.accessoryCount} 项配件)` : ''
const fields = [
escapeNotificationMarkdownInline(asset.code),
escapeNotificationMarkdownInline(asset.name) + accessories,
escapeNotificationMarkdownInline(asset.department, '未归属部门'),
escapeNotificationMarkdownInline(asset.holder, '未领用')
const code = compactNotificationText(asset.code)
const longCode = noticeTextWidth(code) > DISPOSAL_NOTICE_COLUMN_WIDTHS[0]
const accessories = asset.accessoryCount ? `+${asset.accessoryCount}配件` : ''
const columns = [
[longCode ? '' : code],
wrapNoticeColumn(compactNotificationText(asset.name) + accessories, DISPOSAL_NOTICE_COLUMN_WIDTHS[1]),
wrapNoticeColumn(compactNotificationText(asset.department, '未归属部门'), DISPOSAL_NOTICE_COLUMN_WIDTHS[2]),
wrapNoticeColumn(compactNotificationText(asset.holder, '未领用'), DISPOSAL_NOTICE_COLUMN_WIDTHS[3])
]
return `- ${fields.join(' · ')}`
const lines = longCode ? [escapeNotificationMarkdownInline(code)] : []
const height = Math.max(...columns.map(column => column.length))
for (let index = 0; index < height; index++) {
lines.push(renderNoticeColumns(columns.map(column => column[index] || '')))
}
return lines.join('\n\n')
})
const total = `**待审批:** ${rows.length} 笔`
const columnHeading = renderNoticeColumns(['编码', '资产', '部门', '领用人'], true)
const render = (items: string[], part?: string) =>
[...header, ...(part ? [part] : []), total, items.join('\n')].join('\n\n')
[...header, ...(part ? [part] : []), total, columnHeading, ...items].join('\n\n')
const singleCard = render(rows)
if (singleCard.length <= BATCH_DISPOSAL_DINGTALK_BODY_LIMIT) return [singleCard]
@ -204,12 +261,12 @@ export const buildBatchDisposalAppliedDingTalkContents = (input: {
let current = parts[0]
let used = 0
for (const row of rows) {
if (current.length && used + 1 + row.length > rowBudget) {
if (current.length && used + 2 + row.length > rowBudget) {
current = []
parts.push(current)
used = 0
}
used += row.length + (current.length ? 1 : 0)
used += row.length + 2
current.push(row)
}
return parts.map((part, index) => render(part, `第 ${index + 1}/${parts.length} 部分`))
@ -634,7 +691,7 @@ export const createBatchDisposal = async (req: Request, res: Response) => {
level: 'warning', actionUrl: '/workflows/disposals',
metadata: { disposal_ids: ids, equipment_codes: codes, count: ids.length },
dingTalk: {
title: '批量报废待审批', actionTitle: '查看待审批', messageVersion: 'rows-v2',
title: '批量报废待审批', actionTitle: '查看待审批', messageVersion: 'columns-v3',
content, additionalContents
}
})