167 lines
13 KiB
TypeScript
167 lines
13 KiB
TypeScript
import assert from 'node:assert/strict'
|
||
import test from 'node:test'
|
||
import { randomUUID } from 'node:crypto'
|
||
|
||
test('批量报废在本机隔离 MySQL 验证完整资产树、事务和审批通知', {
|
||
skip: process.env.RUN_BUSINESS_DB_TESTS !== 'true'
|
||
}, async t => {
|
||
const url = new URL(process.env.DATABASE_URL || '')
|
||
assert.ok(url.protocol === 'mysql:' && ['127.0.0.1', 'localhost'].includes(url.hostname)
|
||
&& url.port === '13309' && url.pathname === '/equipment_audit' && !url.search && !url.hash)
|
||
const prisma = (await import('../../utils/prisma')).default
|
||
const { createBatchDisposal, previewBatchDisposal } = await import('../disposalController')
|
||
const prefix = `disp-${randomUUID().slice(0, 12)}`
|
||
const userIds: number[] = []
|
||
const personIds: number[] = []
|
||
const env = { YYD_NOTIFICATION_SEND_ENABLED: 'true', YYD_NOTIFICATION_SEND_FULL_ROLLOUT: 'true' }
|
||
const previousEnv = Object.fromEntries(Object.keys(env).map(key => [key, process.env[key]]))
|
||
Object.assign(process.env, env)
|
||
try {
|
||
const applicant = await prisma.user.create({ data: { username: `${prefix}-it`, name: prefix, password: 'local-test-only', role: 'it' } })
|
||
userIds.push(applicant.id)
|
||
const person = await prisma.person.create({ data: { nickname: prefix, real_name: prefix, source_userid: `${prefix}-reviewer` } })
|
||
personIds.push(person.id)
|
||
const reviewer = await prisma.user.create({ data: { username: `${prefix}-reviewer`, name: prefix,
|
||
password: 'local-test-only', role: 'administrative', person_id: person.id } })
|
||
userIds.push(reviewer.id)
|
||
|
||
const data = (suffix: string, parent_id: number | null = null) => ({
|
||
equipment_code: `${prefix}-${suffix}`, equipment_name: `测试资产 ${suffix}`, equipment_type: '报废测试',
|
||
parent_id, mount_status: parent_id ? 'mounted' : 'none', status: '可用',
|
||
total_quantity: 1, remaining_quantity: 1, unit_price: 100, total_value: 100, available_value: 100
|
||
})
|
||
const call = async (handler: typeof createBatchDisposal, body: unknown, ip = '127.0.0.1') => {
|
||
const state = { status: 200, body: null as any }
|
||
const response = { locals: { user: applicant }, status(code: number) { state.status = code; return this },
|
||
json(payload: any) { state.body = payload; return this } }
|
||
await handler({ body, ip } as any, response as any)
|
||
return state
|
||
}
|
||
const submit = (assets: { equipment_id: number; item_ids: number[];
|
||
confirmed_quantities?: { equipment_id: number; total_quantity: number }[] }[], ip?: string) => call(createBatchDisposal,
|
||
{ assets, disposal_reason: '设备老化', disposal_method: '报废', notes: '本机验证' }, ip)
|
||
|
||
const codes = Array.from({ length: 335 }, (_, index) => data(`list-${String(index).padStart(3, '0')}`))
|
||
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]
|
||
const child = await prisma.equipment.create({ data: data('child', root.id) })
|
||
const nested = await prisma.equipment.create({ data: data('nested', child.id) })
|
||
const loaned = await prisma.equipment.create({ data: data('loan') })
|
||
await prisma.borrowRecord.create({ data: { equipment_id: loaned.id, equipment_code: loaned.equipment_code, person_id: person.id,
|
||
person_name: person.real_name, person_nickname: person.nickname, status: '已借出' } })
|
||
const repairing = await prisma.equipment.create({ data: data('repair') })
|
||
await prisma.maintenanceRecord.create({ data: { equipment_id: repairing.id, equipment_code: repairing.equipment_code,
|
||
issue_description: '维修中', estimated_cost: 0, created_by: applicant.id } })
|
||
const pending = await prisma.equipment.create({ data: data('pending') })
|
||
await prisma.disposalRecord.create({ data: { equipment_id: pending.id, equipment_code: pending.equipment_code,
|
||
disposal_reason: '旧待审批', disposal_method: '报废', estimated_value: 0, applied_by: applicant.id } })
|
||
|
||
await t.test('335 个编码只读预检,根包含递归配件,去重与明确阻止各自独立', async t => {
|
||
const start = performance.now()
|
||
const distinctCodes = codes.map(row => row.equipment_code)
|
||
const response = await call(previewBatchDisposal, {
|
||
equipment_codes: [...distinctCodes, ...distinctCodes.slice(0, 166).map(code => ` ${code.toUpperCase()} `)]
|
||
})
|
||
t.diagnostic(`501 条输入(335 条唯一)本机预检用时 ${Math.round(performance.now() - start)} ms`)
|
||
assert.equal(response.status, 200, JSON.stringify(response.body))
|
||
assert.equal(response.body.data.candidates.length, 335)
|
||
assert.deepEqual(response.body.data.candidates.map((row: { equipment_code: string }) => row.equipment_code), distinctCodes)
|
||
assert.deepEqual(response.body.data.duplicate_codes, distinctCodes.slice(0, 166))
|
||
assert.deepEqual(response.body.data.candidates[0].items.map((row: { id: number }) => row.id), [root.id, child.id, nested.id])
|
||
assert.deepEqual(response.body.data.candidates[0].items.map((row: { total_quantity: number }) => row.total_quantity), [1, 1, 1])
|
||
assert.ok(response.body.data.candidates.every((row: { blocked_reason: string | null }) => row.blocked_reason === null))
|
||
const mixed = await call(previewBatchDisposal, {
|
||
equipment_ids: [root.id], equipment_codes: [root.equipment_code.toUpperCase(), child.equipment_code, 'missing-code',
|
||
loaned.equipment_code, repairing.equipment_code, pending.equipment_code]
|
||
})
|
||
assert.equal(mixed.status, 200, JSON.stringify(mixed.body))
|
||
const [first, mounted, missing, borrowed, maintained, disposing] = mixed.body.data.candidates
|
||
assert.equal(first.equipment_id, root.id); assert.equal(mounted.equipment_id, child.id)
|
||
assert.match(mounted.blocked_reason, /挂载/); assert.equal(missing.equipment_id, null); assert.match(missing.blocked_reason, /未找到/)
|
||
assert.match(borrowed.blocked_reason, /未归还/); assert.match(maintained.blocked_reason, /维修/); assert.match(disposing.blocked_reason, /已有/)
|
||
assert.deepEqual(mixed.body.data.duplicate_codes, [root.equipment_code])
|
||
const rootIds = roots.map(row => row.id)
|
||
const mixedAliases = await call(previewBatchDisposal, {
|
||
equipment_ids: [...rootIds, ...rootIds.slice(0, 166)], equipment_codes: distinctCodes
|
||
})
|
||
assert.equal(mixedAliases.status, 200)
|
||
assert.equal(mixedAliases.body.data.candidates.length, 335)
|
||
assert.deepEqual(mixedAliases.body.data.duplicate_codes, distinctCodes)
|
||
const overflow = Array.from({ length: 501 }, (_, index) => `missing-${index}`)
|
||
assert.equal((await call(previewBatchDisposal, { equipment_codes: overflow })).status, 422)
|
||
assert.equal((await call(previewBatchDisposal, { equipment_ids: rootIds, equipment_codes: overflow.slice(0, 166) })).status, 422)
|
||
assert.equal(await prisma.equipment.count({ where: { id: { in: roots.map(row => row.id) }, status: '可用' } }), 335)
|
||
})
|
||
|
||
await t.test('变化后的树必须重新确认,后置审计写入失败回滚前面的全部状态和单据', async () => {
|
||
const independent = roots[1]
|
||
const stale = await submit([{ equipment_id: independent.id, item_ids: [independent.id] }, { equipment_id: root.id, item_ids: [root.id, child.id] }])
|
||
assert.equal(stale.status, 409); assert.match(stale.body.message, new RegExp(nested.equipment_code))
|
||
const overlap = await submit([{ equipment_id: root.id, item_ids: [root.id, child.id, nested.id] }, { equipment_id: child.id, item_ids: [child.id] }])
|
||
assert.equal(overlap.status, 422)
|
||
const quantityMismatch = await submit([{ equipment_id: independent.id, item_ids: [independent.id] },
|
||
{ equipment_id: root.id, item_ids: [root.id, child.id, nested.id],
|
||
confirmed_quantities: [root, child, nested].map(row => ({ equipment_id: row.id, total_quantity: row.id === child.id ? 2 : 1 })) }])
|
||
assert.equal(quantityMismatch.status, 409)
|
||
assert.match(quantityMismatch.body.message, /数量/)
|
||
const occupied = await submit([{ equipment_id: independent.id, item_ids: [independent.id] }, { equipment_id: loaned.id, item_ids: [loaned.id] }])
|
||
assert.equal(occupied.status, 409); assert.match(occupied.body.message, /未归还/)
|
||
const ids = [independent.id, root.id, child.id, nested.id]
|
||
const failed = await submit([{ equipment_id: independent.id, item_ids: [independent.id] },
|
||
{ equipment_id: root.id, item_ids: [root.id, child.id, nested.id] }], 'x'.repeat(60))
|
||
assert.equal(failed.status, 422); assert.match(failed.body.message, /ip_address/)
|
||
assert.equal(await prisma.disposalRecord.count({ where: { equipment_id: { in: ids } } }), 0)
|
||
assert.equal(await prisma.equipment.count({ where: { id: { in: ids }, status: '可用' } }), 4)
|
||
assert.equal(await prisma.notification.count({ where: { type: 'disposal', metadata: { contains: prefix } } }), 0)
|
||
})
|
||
|
||
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`)
|
||
assert.equal(result.status, 200, JSON.stringify(result.body))
|
||
const { count, disposal_ids: ids } = result.body.data
|
||
assert.equal(count, 335); assert.equal(new Set(ids).size, 335)
|
||
assert.equal(await prisma.disposalRecord.count({ where: { id: { in: ids }, status: 'pending', applied_by: applicant.id } }), 335)
|
||
assert.equal(await prisma.disposalAction.count({ where: { disposal_id: { in: ids }, action_type: 'applied' } }), 335)
|
||
assert.equal(await prisma.operationLog.count({ where: { user_id: applicant.id, operation_type: '报废申请' } }), 335)
|
||
const detail = await prisma.disposalItem.findMany({ where: { disposal_id: ids[0] } })
|
||
assert.deepEqual(new Set(detail.map(row => row.equipment_id)), new Set([root.id, child.id, nested.id]))
|
||
assert.equal(await prisma.equipment.count({ where: { id: { in: [...roots.map(row => row.id), child.id, nested.id] }, status: '待报废' } }), 337)
|
||
const notices = await prisma.notification.findMany({ where: { type: 'disposal', metadata: { contains: prefix } }, include: { recipients: true } })
|
||
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 repeated = await submit([{ equipment_id: root.id, item_ids: [root.id, child.id, nested.id] }])
|
||
assert.equal(repeated.status, 409)
|
||
})
|
||
} finally {
|
||
for (const [key, value] of Object.entries(previousEnv)) {
|
||
if (value === undefined) delete process.env[key]
|
||
else process.env[key] = value
|
||
}
|
||
try {
|
||
await prisma.$transaction(async tx => {
|
||
const fixtures = await tx.equipment.findMany({ where: { equipment_code: { startsWith: prefix } }, select: { id: true } })
|
||
const equipment_id = { in: fixtures.map(row => row.id) }
|
||
const disposals = await tx.disposalRecord.findMany({ where: { equipment_id }, select: { id: true } })
|
||
const disposalIds = disposals.map(row => row.id)
|
||
await tx.dingTalkDelivery.deleteMany({ where: { business_type: 'disposal', business_id: { in: disposalIds } } })
|
||
await tx.notification.deleteMany({ where: { type: 'disposal', metadata: { contains: prefix } } })
|
||
await tx.operationLog.deleteMany({ where: { user_id: { in: userIds } } })
|
||
await tx.disposalRecord.deleteMany({ where: { id: { in: disposalIds } } })
|
||
await tx.borrowRecord.deleteMany({ where: { equipment_id } })
|
||
await tx.maintenanceRecord.deleteMany({ where: { equipment_id } })
|
||
await tx.equipment.updateMany({ where: { id: equipment_id }, data: { parent_id: null } })
|
||
await tx.equipment.deleteMany({ where: { id: equipment_id } })
|
||
await tx.user.deleteMany({ where: { id: { in: userIds } } })
|
||
await tx.person.deleteMany({ where: { id: { in: personIds } } })
|
||
}, { timeout: 20000 })
|
||
} finally { await prisma.$disconnect() }
|
||
}
|
||
})
|