From 943196bbc06346abc0b95cf8cb76bab994a0bc78 Mon Sep 17 00:00:00 2001 From: WuYongJie Date: Tue, 10 Nov 2026 18:26:31 +0800 Subject: [PATCH] List assets in batch disposal DingTalk notices --- .../disposalBatch.integration.test.ts | 37 ++++++-- .../disposalController.state-machine.test.ts | 19 ++++ backend/src/controllers/disposalController.ts | 86 +++++++++++++++++-- .../services/businessNotificationService.ts | 12 ++- backend/src/utils/disposalSubmission.ts | 4 +- 5 files changed, 140 insertions(+), 18 deletions(-) diff --git a/backend/src/controllers/__tests__/disposalBatch.integration.test.ts b/backend/src/controllers/__tests__/disposalBatch.integration.test.ts index 18d53f1..4b92613 100644 --- a/backend/src/controllers/__tests__/disposalBatch.integration.test.ts +++ b/backend/src/controllers/__tests__/disposalBatch.integration.test.ts @@ -45,6 +45,8 @@ 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 codes = Array.from({ length: 335 }, (_, index) => data(`list-${String(index).padStart(3, '0')}`)) await prisma.equipment.createMany({ data: codes }) @@ -130,7 +132,7 @@ test('批量报废在本机隔离 MySQL 验证完整资产树、事务和审批 assert.equal(await prisma.notification.count({ where: { type: 'disposal', metadata: { contains: prefix } } }), 0) }) - await t.test('335 根各生成一张待审批单,整树进入待报废,只发送一条聚合审批通知', async t => { + await t.test('335 根各生成一张待审批单,站内通知一条,钉钉分卡完整列出明细', async t => { const start = performance.now() const result = await submit(roots.map(row => ({ equipment_id: row.id, item_ids: row.id === root.id ? [root.id, child.id, nested.id] : [row.id] }))) t.diagnostic(`335 根本机提交用时 ${Math.round(performance.now() - start)} ms`) @@ -147,9 +149,23 @@ test('批量报废在本机隔离 MySQL 验证完整资产树、事务和审批 assert.equal(notices.length, 1); assert.equal(notices[0].action_url, '/workflows/disposals') assert.deepEqual(JSON.parse(notices[0].metadata!).disposal_ids, ids) assert.ok(notices[0].recipients.some(row => row.user_id === reviewer.id)) - const deliveries = await prisma.dingTalkDelivery.findMany({ where: { business_type: 'disposal', business_id: { in: ids }, recipient_user_id: reviewer.id } }) - assert.equal(deliveries.length, 1); assert.equal(deliveries[0].status, 'pending') - assert.match(JSON.parse(deliveries[0].payload_json).content, /335 笔/) + const deliveries = await prisma.dingTalkDelivery.findMany({ where: { business_type: 'disposal', business_id: { in: ids }, + recipient_user_id: reviewer.id }, orderBy: { id: 'asc' } }) + assert.ok(deliveries.length > 1) + assert.equal(new Set(deliveries.map(delivery => delivery.idempotency_key)).size, deliveries.length) + const cards = deliveries.map((delivery, index) => { + assert.equal(delivery.status, 'pending') + 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.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 项配件)'} · 未归属部门 · 未领用`)) const repeated = await submit([{ equipment_id: root.id, item_ids: [root.id, child.id, nested.id] }]) assert.equal(repeated.status, 409) }) @@ -176,9 +192,12 @@ test('批量报废在本机隔离 MySQL 验证完整资产树、事务和审批 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 unselected = await prisma.equipment.create({ data: data('auto-unselected') }) - const ready = await prisma.equipment.create({ data: data('auto-ready') }) + const ready = await prisma.equipment.create({ data: { ...data('auto-ready'), 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) const anotherBorrowId = await borrow(another.id) + await prisma.borrowRecord.update({ where: { id: anotherBorrowId }, data: { person_nickname: '', person_name: '实际姓名' } }) const unselectedBorrowId = await borrow(unselected.id) const [offered, offeredAnother, offeredUnselected, available] = await previewReturn(checkedOut.id, another.id, unselected.id, ready.id) for (const candidate of [offered, offeredAnother, offeredUnselected]) { @@ -221,6 +240,14 @@ test('批量报废在本机隔离 MySQL 验证完整资产树、事务和审批 assert.equal(succeeded.status, 200, JSON.stringify(succeeded.body)) const ids = succeeded.body.data.disposal_ids as number[] assert.equal(ids.length, 3) + const delivery = await prisma.dingTalkDelivery.findFirstOrThrow({ where: { event_type: 'disposal_applied', + 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} · 实际姓名` + ]) assert.equal(await prisma.disposalRecord.count({ where: { id: { in: ids }, status: 'pending' } }), 3) assert.equal(await pendingNotices(), noticeCount + 1) const returned = await prisma.borrowRecord.findMany({ where: { id: borrowIds }, orderBy: { id: 'asc' } }) diff --git a/backend/src/controllers/__tests__/disposalController.state-machine.test.ts b/backend/src/controllers/__tests__/disposalController.state-machine.test.ts index 9c6d157..0eedb8b 100644 --- a/backend/src/controllers/__tests__/disposalController.state-machine.test.ts +++ b/backend/src/controllers/__tests__/disposalController.state-machine.test.ts @@ -4,6 +4,7 @@ import assert from 'node:assert/strict' import prisma from '../../utils/prisma' import { approveDisposal, + buildBatchDisposalAppliedDingTalkContents, buildDisposalAppliedDingTalkContent, buildDisposalApprovedDingTalkContent, buildDisposalCompletedDingTalkContent, @@ -14,6 +15,24 @@ import { } from '../disposalController' 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 部分/) +}) + const rootEquipment = { id: 10, equipment_code: 'JS-PC-0010', diff --git a/backend/src/controllers/disposalController.ts b/backend/src/controllers/disposalController.ts index 4938fc4..199de43 100644 --- a/backend/src/controllers/disposalController.ts +++ b/backend/src/controllers/disposalController.ts @@ -162,6 +162,59 @@ export const buildDisposalAppliedDingTalkContent = (input: { '> 请核对资产及配件明细后处理。' ].join('\n\n') +// The notification center reserves up to 120 characters for the visible title. +const BATCH_DISPOSAL_DINGTALK_BODY_LIMIT = 4800 - 120 - '### \n\n'.length + +export const buildBatchDisposalAppliedDingTalkContents = (input: { + appliedAt: Date + applicantName: unknown + reason: string + assets: { + code: string + name: string + department?: string + holder?: string + accessoryCount: number + }[] +}) => { + const header = [ + `**申请时间:** ${formatBeijingDateTime(input.appliedAt)}`, + `**申请人:** ${escapeNotificationMarkdownInline(input.applicantName)}`, + `**报废原因:** ${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, '未领用') + ] + return `- ${fields.join(' · ')}` + }) + const total = `**待审批:** ${rows.length} 笔` + const render = (items: string[], part?: string) => + [...header, ...(part ? [part] : []), total, items.join('\n')].join('\n\n') + + const singleCard = render(rows) + if (singleCard.length <= BATCH_DISPOSAL_DINGTALK_BODY_LIMIT) return [singleCard] + + const rowBudget = BATCH_DISPOSAL_DINGTALK_BODY_LIMIT - render([], `第 ${rows.length}/${rows.length} 部分`).length + const parts: string[][] = [[]] + let current = parts[0] + let used = 0 + for (const row of rows) { + if (current.length && used + 1 + row.length > rowBudget) { + current = [] + parts.push(current) + used = 0 + } + used += row.length + (current.length ? 1 : 0) + current.push(row) + } + return parts.map((part, index) => render(part, `第 ${index + 1}/${parts.length} 部分`)) +} + export const buildDisposalApprovedDingTalkContent = (input: { approvedAt: Date equipmentName: unknown @@ -499,6 +552,13 @@ export const createBatchDisposal = async (req: Request, res: Response) => { await lockEquipmentRows(tx, [...lockedIds]) const roots = await tx.equipment.findMany({ where: { id: { in: rootIds } }, select: disposalTreeSelect }) if (roots.length !== rootIds.length) throw new DisposalConflictError('有主资产已不存在,请重新预检') + const originalDepartments = new Map(roots.map(root => [root.id, root.department_id])) + const departmentIds = [...new Set(roots.flatMap(root => root.department_id === null ? [] : [root.department_id]))] + const departments = departmentIds.length ? await tx.department.findMany({ + where: { id: { in: departmentIds } }, select: { id: true, name: true } + }) : [] + const departmentNames = new Map(departments.map(department => [department.id, department.name])) + const holders = new Map() let trees = await loadDisposalTrees(tx, roots) for (const id of rootIds) { const tree = trees.get(id)! @@ -524,6 +584,7 @@ export const createBatchDisposal = async (req: Request, res: Response) => { return { items, borrowRecord: eligible.record } }) for (const { items, borrowRecord } of returns) { + holders.set(items[0].id, borrowRecord.person_nickname.trim() || borrowRecord.person_name.trim() || '未登记领用人') await completeLockedBorrowReturn(tx, { items, borrowRecord, returnCondition: '正常', operatedBy: userId, reason: '批量报废前归还入库', requireUnreturned: true @@ -551,6 +612,21 @@ export const createBatchDisposal = async (req: Request, res: Response) => { })) }) const recipients = await getSubmissionRecipients(tx, userId) const preview = codes.slice(0, 10).join('、') + (codes.length > 10 ? ` 等 ${codes.length} 个` : '') + const [content, ...additionalContents] = buildBatchDisposalAppliedDingTalkContents({ + appliedAt: created[0].applied_at, + applicantName: res.locals.user?.name || userName, + reason: input.reason, + assets: rootIds.map(id => { + const tree = trees.get(id)! + const root = tree[0] + const departmentId = originalDepartments.get(id) + return { + code: root.equipment_code, name: root.equipment_name, + department: departmentId == null ? undefined : departmentNames.get(departmentId), + holder: holders.get(id), accessoryCount: tree.length - 1 + } + }) + }) await createBusinessNotification(tx, { ...recipients, eventType: 'disposal_applied', businessType: 'disposal', businessId: ids[0], title: `待审批报废:${ids.length} 笔`, @@ -558,14 +634,8 @@ 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: 'v1', - content: [ - `**申请时间:** ${formatBeijingDateTime(created[0].applied_at)}`, - `**待审批:** ${ids.length} 笔(${escapeNotificationMarkdownInline(preview)})`, - `**申请人:** ${escapeNotificationMarkdownInline(res.locals.user?.name || userName)}`, - `**报废原因:** ${escapeNotificationMarkdownInline(input.reason.slice(0, 300))}`, - '> 请在报废流程列表中逐笔核对并审批。' - ].join('\n\n') + title: '批量报废待审批', actionTitle: '查看待审批', messageVersion: 'rows-v2', + content, additionalContents } }) return ids diff --git a/backend/src/services/businessNotificationService.ts b/backend/src/services/businessNotificationService.ts index d712267..dbb760e 100644 --- a/backend/src/services/businessNotificationService.ts +++ b/backend/src/services/businessNotificationService.ts @@ -162,6 +162,7 @@ export const createBusinessNotification = async ( dingTalk: { title: string content: string + additionalContents?: string[] actionTitle: string messageVersion?: string } @@ -181,8 +182,11 @@ export const createBusinessNotification = async ( attentionRecipients.length === 0 ) return null - const messageVersion = compactNotificationText(input.dingTalk.messageVersion, 'v1', 30) - const deliveries = dingTalkRecipients.map((recipient) => { + const baseVersion = compactNotificationText(input.dingTalk.messageVersion, 'v1', 30) + const contents = [input.dingTalk.content, ...(input.dingTalk.additionalContents || [])] + const deliveries = dingTalkRecipients.flatMap(recipient => contents.map((content, index) => { + const partSuffix = index ? `.part-${index + 1}` : '' + const messageVersion = baseVersion.slice(0, 30 - partSuffix.length) + partSuffix const dingtalkUserId = recipient.person.source_userid.trim() const idempotencyKey = `${input.eventType}:${input.businessId}:${dingtalkUserId}:${messageVersion}` if (idempotencyKey.length > 160) { @@ -198,13 +202,13 @@ export const createBusinessNotification = async ( provider_type: 'notification_center', payload_json: JSON.stringify({ title: input.dingTalk.title, - content: input.dingTalk.content, + content, action_title: input.dingTalk.actionTitle, action_url: input.actionUrl, message_version: messageVersion }) } - }) + })) const notification = stationRecipients.length > 0 ? await client.notification.create({ diff --git a/backend/src/utils/disposalSubmission.ts b/backend/src/utils/disposalSubmission.ts index ab75490..209b388 100644 --- a/backend/src/utils/disposalSubmission.ts +++ b/backend/src/utils/disposalSubmission.ts @@ -73,6 +73,8 @@ type DisposalBorrow = { id: number equipment_id: number person_id: number + person_name: string + person_nickname: string return_time: Date | null children_snapshot: string | null updated_at: Date @@ -88,7 +90,7 @@ export const loadDisposalAutoReturnBorrows = async ( const byAsset = new Map() if (!ids.length) return byAsset const rows = await client.$queryRaw(Prisma.sql` - SELECT id, equipment_id, person_id, return_time, children_snapshot, updated_at + SELECT id, equipment_id, person_id, person_name, person_nickname, return_time, children_snapshot, updated_at FROM borrow_record WHERE equipment_id IN (${Prisma.join(ids)}) AND status = ${'已借出'} ORDER BY id ${lock ? Prisma.sql`FOR UPDATE` : Prisma.empty}