Add batch approval for asset disposal
This commit is contained in:
parent
994643629e
commit
db20368446
@ -9,7 +9,7 @@ test('批量报废在本机隔离 MySQL 验证完整资产树、事务和审批
|
||||
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 { approveBatchDisposal, approveDisposal, createBatchDisposal, getDisposalList, previewBatchDisposal } = await import('../disposalController')
|
||||
const { borrowEquipment, returnEquipment } = await import('../borrowController')
|
||||
const prefix = `disp-${randomUUID().slice(0, 12)}`
|
||||
const userIds: number[] = []
|
||||
@ -33,11 +33,12 @@ test('批量报废在本机隔离 MySQL 验证完整资产树、事务和审批
|
||||
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 call = async (handler: typeof createBatchDisposal, body: unknown, ip = '127.0.0.1',
|
||||
actor = applicant, params?: Record<string, string>, query?: Record<string, string>) => {
|
||||
const state = { status: 200, body: null as any }
|
||||
const response = { locals: { user: applicant }, status(code: number) { state.status = code; return this },
|
||||
const response = { locals: { user: actor }, 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)
|
||||
await handler({ body, ip, params, query } as any, response as any)
|
||||
return state
|
||||
}
|
||||
const submit = (assets: { equipment_id: number; item_ids: number[];
|
||||
@ -284,6 +285,126 @@ test('批量报废在本机隔离 MySQL 验证完整资产树、事务和审批
|
||||
assert.equal((await prisma.borrowRecord.findUniqueOrThrow({ where: { id: changingBorrowId } })).return_time, null)
|
||||
assert.equal(await prisma.disposalRecord.count({ where: { equipment_id: changingRoot.id } }), 0)
|
||||
})
|
||||
|
||||
const approveBatch = (disposal_ids: unknown[], approved: unknown, reject_reason?: string) =>
|
||||
call(approveBatchDisposal, { disposal_ids, approved, reject_reason }, '127.0.0.1', reviewer)
|
||||
const apply = async (equipmentId: number, itemIds = [equipmentId], actor = applicant) => {
|
||||
const result = await call(createBatchDisposal, { assets: [{ equipment_id: equipmentId, item_ids: itemIds }],
|
||||
disposal_reason: '批量审批测试', disposal_method: '报废' }, '127.0.0.1', actor)
|
||||
assert.equal(result.status, 200, JSON.stringify(result.body))
|
||||
return result.body.data.disposal_ids[0] as number
|
||||
}
|
||||
|
||||
await t.test('批量审批 336 张完整单据,按申请人合并结果且同时间列表顺序稳定', async () => {
|
||||
const applicantPerson = await prisma.person.create({ data: {
|
||||
nickname: `${prefix}-applicant`, real_name: prefix, source_userid: `${prefix}-applicant`
|
||||
} })
|
||||
personIds.push(applicantPerson.id)
|
||||
await prisma.user.update({ where: { id: applicant.id }, data: { person_id: applicantPerson.id } })
|
||||
const otherRoot = await prisma.equipment.create({ data: data('approval-other') })
|
||||
const otherId = await apply(otherRoot.id, [otherRoot.id], reviewer)
|
||||
const applied = await prisma.disposalRecord.findMany({ where: { equipment_id: { in: roots.map(row => row.id) } },
|
||||
orderBy: { id: 'desc' } })
|
||||
assert.equal(applied.length, 335)
|
||||
const [secondNewest, oldest] = [applied[0], applied[1]]
|
||||
await prisma.disposalRecord.updateMany({ where: { id: { in: [secondNewest.id, oldest.id] } },
|
||||
data: { created_at: new Date('2099-01-01T00:00:00.000Z') } })
|
||||
for (const [index, expected] of [secondNewest.id, oldest.id].entries()) {
|
||||
const list = await call(getDisposalList, {}, '127.0.0.1', reviewer, undefined, {
|
||||
scope: 'pending', keyword: `${prefix}-list-`, page: String(index + 1), pageSize: '1'
|
||||
})
|
||||
assert.equal(list.status, 200)
|
||||
assert.equal(list.body.data.list[0].id, expected)
|
||||
}
|
||||
|
||||
const ids = [...applied.map(row => row.id), otherId]
|
||||
const result = await approveBatch(ids, true)
|
||||
assert.equal(result.status, 200, JSON.stringify(result.body))
|
||||
assert.deepEqual(result.body.data, { count: 336, disposal_ids: ids })
|
||||
assert.equal(await prisma.disposalRecord.count({ where: { id: { in: ids }, status: 'approved', approved_by: reviewer.id } }), 336)
|
||||
assert.equal(await prisma.disposalAction.count({ where: { disposal_id: { in: ids }, action_type: 'approved', operator_id: reviewer.id } }), 336)
|
||||
assert.equal(await prisma.operationLog.count({ where: { user_id: reviewer.id, operation_type: '报废审批通过',
|
||||
equipment_id: { in: [...roots.map(row => row.id), otherRoot.id] } } }), 336)
|
||||
assert.equal(await prisma.equipment.count({ where: { id: { in: [root.id, child.id, nested.id] }, status: '待报废' } }), 3)
|
||||
|
||||
const notices = await prisma.notification.findMany({ where: {
|
||||
type: 'disposal', title: { startsWith: '报废批量审批已通过' }, metadata: { contains: prefix }
|
||||
}, include: { recipients: true } })
|
||||
assert.equal(notices.length, 2)
|
||||
const groupedIds = new Map(notices.map(row => {
|
||||
const metadata = JSON.parse(row.metadata!)
|
||||
return [metadata.business_id, metadata.disposal_ids]
|
||||
}))
|
||||
assert.deepEqual(groupedIds.get(ids[0]), ids.slice(0, -1))
|
||||
assert.deepEqual(groupedIds.get(otherId), [otherId])
|
||||
assert.equal(notices.filter(row => row.recipients.some(recipient => recipient.user_id === applicant.id)).length, 1)
|
||||
const delivery = await prisma.dingTalkDelivery.findMany({ where: { event_type: 'disposal_approved',
|
||||
business_id: { in: ids }, recipient_user_id: applicant.id } })
|
||||
assert.equal(delivery.length, 1)
|
||||
assert.match(JSON.parse(delivery[0].payload_json).content, /335 笔已通过/)
|
||||
})
|
||||
|
||||
await t.test('批量驳回共享必填理由并恢复每件资产申请前状态', async () => {
|
||||
const first = await prisma.equipment.create({ data: data('rejection-root') })
|
||||
const part = await prisma.equipment.create({ data: { ...data('rejection-part', first.id), status: '已损坏' } })
|
||||
const second = await prisma.equipment.create({ data: data('rejection-other') })
|
||||
const firstId = await apply(first.id, [first.id, part.id])
|
||||
const secondId = await apply(second.id)
|
||||
await prisma.disposalItem.updateMany({ where: { disposal_id: secondId }, data: { snapshot_json: '{"status":"可用"}' } })
|
||||
const ids = [firstId, secondId]
|
||||
assert.equal((await approveBatch(ids, false, ' ')).status, 422)
|
||||
const result = await approveBatch(ids, false, ' 暂不处置 ')
|
||||
assert.equal(result.status, 200, JSON.stringify(result.body))
|
||||
const restored = await prisma.equipment.findMany({ where: { id: { in: [first.id, part.id, second.id] } }, orderBy: { id: 'asc' } })
|
||||
assert.deepEqual(restored.map(row => row.status), ['可用', '已损坏', '可用'])
|
||||
assert.equal(await prisma.disposalRecord.count({ where: { id: { in: ids }, status: 'rejected', reject_reason: '暂不处置' } }), 2)
|
||||
assert.equal(await prisma.disposalAction.count({ where: { disposal_id: { in: ids }, action_type: 'rejected', detail: '暂不处置' } }), 2)
|
||||
assert.equal(await prisma.operationLog.count({ where: { user_id: reviewer.id, operation_type: '报废审批驳回',
|
||||
equipment_id: { in: [first.id, second.id] } } }), 2)
|
||||
const grouped = await prisma.dingTalkDelivery.findMany({ where: { event_type: 'disposal_rejected',
|
||||
business_id: { in: ids }, recipient_user_id: applicant.id } })
|
||||
assert.equal(grouped.length, 1)
|
||||
assert.match(JSON.parse(grouped[0].payload_json).content, /暂不处置/)
|
||||
})
|
||||
|
||||
await t.test('错误单据整批回滚,历史缺数量仍可单项确认,反序并发只成功一次', async () => {
|
||||
const current = await prisma.equipment.create({ data: data('approval-current') })
|
||||
const historic = await prisma.equipment.create({ data: data('approval-legacy') })
|
||||
const currentId = await apply(current.id)
|
||||
const historicId = await apply(historic.id)
|
||||
await prisma.disposalItem.updateMany({ where: { disposal_id: historicId }, data: { snapshot_json: '{"status":"可用"}' } })
|
||||
for (const ids of [[], [currentId, currentId], [0], [String(currentId)], Array.from({ length: 501 }, (_, index) => index + 1)]) {
|
||||
assert.equal((await approveBatch(ids, true)).status, 422)
|
||||
}
|
||||
assert.equal((await approveBatch([currentId], 'true')).status, 422)
|
||||
const conflicted = await approveBatch([currentId, historicId], true)
|
||||
assert.equal(conflicted.status, 409)
|
||||
assert.match(conflicted.body.message, new RegExp(historic.equipment_code))
|
||||
assert.match(conflicted.body.message, /逐件核对/)
|
||||
const ids = [currentId, historicId]
|
||||
assert.equal(await prisma.disposalRecord.count({ where: { id: { in: ids }, status: 'pending' } }), 2)
|
||||
assert.equal(await prisma.disposalAction.count({ where: { disposal_id: { in: ids }, action_type: 'approved' } }), 0)
|
||||
assert.equal(await prisma.operationLog.count({ where: { user_id: reviewer.id, operation_type: '报废审批通过',
|
||||
equipment_id: { in: [current.id, historic.id] } } }), 0)
|
||||
const single = await call(approveDisposal, { approved: true, confirmed_quantities: [{ equipment_id: historic.id, total_quantity: 1 }] },
|
||||
'127.0.0.1', reviewer, { id: String(historicId) })
|
||||
assert.equal(single.status, 200, JSON.stringify(single.body))
|
||||
assert.equal((await approveBatch(ids, true)).status, 409)
|
||||
assert.equal((await prisma.disposalRecord.findUniqueOrThrow({ where: { id: currentId } })).status, 'pending')
|
||||
|
||||
const concurrent = await prisma.equipment.create({ data: data('approval-concurrent') })
|
||||
const concurrentId = await apply(concurrent.id)
|
||||
const outcomes = await Promise.all([
|
||||
approveBatch([currentId, concurrentId], true),
|
||||
approveBatch([concurrentId, currentId], false, '保留使用')
|
||||
])
|
||||
assert.deepEqual(outcomes.map(row => row.status).sort(), [200, 409])
|
||||
const completed = await prisma.disposalRecord.findMany({ where: { id: { in: [currentId, concurrentId] } } })
|
||||
assert.deepEqual(completed.map(row => row.status), [outcomes[0].status === 200 ? 'approved' : 'rejected',
|
||||
outcomes[0].status === 200 ? 'approved' : 'rejected'])
|
||||
assert.equal(await prisma.disposalAction.count({ where: { disposal_id: { in: [currentId, concurrentId] },
|
||||
action_type: { in: ['approved', 'rejected'] } } }), 2)
|
||||
})
|
||||
} finally {
|
||||
for (const [key, value] of Object.entries(previousEnv)) {
|
||||
if (value === undefined) delete process.env[key]
|
||||
@ -296,7 +417,10 @@ test('批量报废在本机隔离 MySQL 验证完整资产树、事务和审批
|
||||
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.notification.deleteMany({ where: { type: 'disposal', OR: [
|
||||
{ metadata: { contains: prefix } },
|
||||
{ action_url: { in: disposalIds.map(id => `/workflows/disposals/${id}`) } }
|
||||
] } })
|
||||
await tx.operationLog.deleteMany({ where: { user_id: { in: userIds } } })
|
||||
await tx.disposalRecord.deleteMany({ where: { id: { in: disposalIds } } })
|
||||
await tx.borrowRecord.deleteMany({ where: { equipment_id } })
|
||||
|
||||
@ -641,7 +641,7 @@ export const getDisposalList = async (req: Request, res: Response) => {
|
||||
where,
|
||||
skip,
|
||||
take: currentPageSize,
|
||||
orderBy: { created_at: 'desc' },
|
||||
orderBy: [{ created_at: 'desc' }, { id: 'desc' }],
|
||||
include: {
|
||||
equipment: { select: { equipment_name: true, equipment_type: true, unit_price: true } },
|
||||
applier: { select: { id: true, name: true, username: true } },
|
||||
@ -712,6 +712,22 @@ export const getDisposalDetail = async (req: Request, res: Response) => {
|
||||
}
|
||||
|
||||
const disposalDecisionInclude = { items: { include: { equipment: true } } } as const
|
||||
type DisposalDecisionRecord = Prisma.DisposalRecordGetPayload<{ include: typeof disposalDecisionInclude }>
|
||||
|
||||
const getDisposalDecisionRoot = (disposal: DisposalDecisionRecord, expectedStatus: string, equipmentIds: Set<number>) => {
|
||||
if (disposal.status !== expectedStatus) throw new DisposalConflictError('该申请已被其他人处理,请刷新后查看')
|
||||
const root = disposal.items.find(item => item.equipment_id === disposal.equipment_id)?.equipment
|
||||
if (!root || root.parent_id !== null || !equipmentIds.has(root.id) || disposal.items.some(item => !equipmentIds.has(item.equipment_id))) {
|
||||
throw new DisposalConflictError('报废明细范围已变化或缺少主资产,请先核查')
|
||||
}
|
||||
return root
|
||||
}
|
||||
|
||||
const assertDisposalDecisionTree = (disposal: DisposalDecisionRecord, tree: DisposalTreeItem[]) => {
|
||||
assertDisposalItemsConfirmed(tree, disposal.items.map(item => item.equipment_id))
|
||||
const changedItem = disposal.items.find(item => item.equipment.status !== '待报废' || item.equipment.parent_id !== item.parent_equipment_id)
|
||||
if (changedItem) throw new DisposalConflictError(`资产 ${changedItem.equipment_code} 的状态或挂载关系已变化,请先核查`)
|
||||
}
|
||||
|
||||
const loadLockedDisposalDecision = async (tx: Prisma.TransactionClient, id: number, expectedStatus: string) => {
|
||||
const initial = await tx.disposalRecord.findUnique({ where: { id }, include: disposalDecisionInclude })
|
||||
@ -719,21 +735,16 @@ const loadLockedDisposalDecision = async (tx: Prisma.TransactionClient, id: numb
|
||||
const equipmentIds = new Set([initial.equipment_id, ...initial.items.map(item => item.equipment_id)])
|
||||
await lockEquipmentRows(tx, [...equipmentIds])
|
||||
const disposal = await tx.disposalRecord.findUnique({ where: { id }, include: disposalDecisionInclude })
|
||||
if (!disposal || disposal.status !== expectedStatus) throw new DisposalConflictError('该申请已被其他人处理,请刷新后查看')
|
||||
const root = disposal.items.find(item => item.equipment_id === disposal.equipment_id)?.equipment
|
||||
if (!root || root.parent_id !== null || !equipmentIds.has(root.id) || disposal.items.some(item => !equipmentIds.has(item.equipment_id))) {
|
||||
throw new DisposalConflictError('报废明细范围已变化或缺少主资产,请先核查')
|
||||
}
|
||||
if (!disposal) throw new DisposalConflictError('该申请已被其他人处理,请刷新后查看')
|
||||
const root = getDisposalDecisionRoot(disposal, expectedStatus, equipmentIds)
|
||||
const trees = await loadDisposalTrees(tx, [root])
|
||||
assertDisposalItemsConfirmed(trees.get(root.id)!, disposal.items.map(item => item.equipment_id))
|
||||
const changedItem = disposal.items.find(item => item.equipment.status !== '待报废' || item.equipment.parent_id !== item.parent_equipment_id)
|
||||
if (changedItem) throw new DisposalConflictError(`资产 ${changedItem.equipment_code} 的状态或挂载关系已变化,请先核查`)
|
||||
assertDisposalDecisionTree(disposal, trees.get(root.id)!)
|
||||
return disposal
|
||||
}
|
||||
|
||||
const verifyDisposalQuantities = async (
|
||||
tx: Prisma.TransactionClient,
|
||||
disposal: Awaited<ReturnType<typeof loadLockedDisposalDecision>>,
|
||||
disposal: DisposalDecisionRecord,
|
||||
confirmation?: Map<number, number>
|
||||
) => {
|
||||
if (confirmation) assertConfirmedDisposalQuantities(disposal.items.map(item => item.equipment), confirmation)
|
||||
@ -792,22 +803,72 @@ const readConfirmedDisposalQuantities = (input: unknown) => {
|
||||
return confirmed
|
||||
}
|
||||
|
||||
const readDisposalDecision = (body: { approved?: unknown; reject_reason?: unknown }) => {
|
||||
const { approved, reject_reason } = body
|
||||
if (typeof approved !== 'boolean') {
|
||||
throw Object.assign(new Error('审批结果必须明确为通过或驳回'), { status: 422 })
|
||||
}
|
||||
const rejectReason = typeof reject_reason === 'string' ? reject_reason.trim() : ''
|
||||
if (!approved && !rejectReason) {
|
||||
throw Object.assign(new Error('驳回原因不能为空'), { status: 422 })
|
||||
}
|
||||
return { approved, rejectReason }
|
||||
}
|
||||
|
||||
type DisposalDecision = ReturnType<typeof readDisposalDecision>
|
||||
|
||||
const writeDisposalDecision = async (
|
||||
tx: Prisma.TransactionClient,
|
||||
disposal: DisposalDecisionRecord,
|
||||
decision: DisposalDecision,
|
||||
userId: number,
|
||||
approvedAt: Date,
|
||||
confirmation?: Map<number, number>
|
||||
) => {
|
||||
const { approved, rejectReason } = decision
|
||||
if (approved) await verifyDisposalQuantities(tx, disposal, confirmation)
|
||||
const nextStatus = approved ? 'approved' : 'rejected'
|
||||
const updated = await tx.disposalRecord.updateMany({
|
||||
where: { id: disposal.id, status: 'pending' },
|
||||
data: {
|
||||
status: nextStatus, approved_by: userId, approved_at: approvedAt,
|
||||
reject_reason: approved ? null : rejectReason
|
||||
}
|
||||
})
|
||||
if (updated.count !== 1) {
|
||||
throw new DisposalConflictError('该申请已被其他人处理,请刷新后查看')
|
||||
}
|
||||
if (!approved) {
|
||||
for (const item of disposal.items) {
|
||||
await updateEquipmentLifecycle(tx, item.equipment, item.pre_status, '待报废', item.parent_equipment_id)
|
||||
}
|
||||
}
|
||||
await tx.disposalAction.create({
|
||||
data: {
|
||||
disposal_id: disposal.id, action_type: nextStatus, operator_id: userId,
|
||||
from_status: 'pending', to_status: nextStatus, detail: approved ? null : rejectReason
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
const getDisposalDecisionOperation = (disposal: DisposalDecisionRecord, approved: boolean) => ({
|
||||
operation_type: approved ? '报废审批通过' : '报废审批驳回',
|
||||
operation_details: `${approved ? '批准' : '驳回'}资产 ${disposal.equipment_code} 的报废申请`
|
||||
})
|
||||
|
||||
export const approveDisposal = async (req: Request, res: Response) => {
|
||||
try {
|
||||
const disposalId = Number(req.params.id)
|
||||
const { approved, reject_reason, confirmed_quantities, reconfirm_quantities } = req.body as {
|
||||
const body = (req.body || {}) as {
|
||||
approved?: boolean
|
||||
reject_reason?: string
|
||||
confirmed_quantities?: unknown
|
||||
reconfirm_quantities?: boolean
|
||||
}
|
||||
const decision = readDisposalDecision(body)
|
||||
const { approved, rejectReason } = decision
|
||||
const { confirmed_quantities, reconfirm_quantities } = body
|
||||
const userId = Number(res.locals.user?.id)
|
||||
if (typeof approved !== 'boolean') {
|
||||
return errorResponse(res, '审批结果必须明确为通过或驳回', 422)
|
||||
}
|
||||
if (!approved && !reject_reason?.trim()) {
|
||||
return errorResponse(res, '驳回原因不能为空', 422)
|
||||
}
|
||||
if (reconfirm_quantities === true && !approved) {
|
||||
return errorResponse(res, '数量复核必须明确确认通过', 422)
|
||||
}
|
||||
@ -833,45 +894,8 @@ export const approveDisposal = async (req: Request, res: Response) => {
|
||||
|
||||
const result = await prisma.$transaction(async (tx) => {
|
||||
const disposal = await loadLockedDisposalDecision(tx, disposalId, 'pending')
|
||||
if (approved) await verifyDisposalQuantities(tx, disposal, confirmation)
|
||||
|
||||
const nextStatus = approved ? 'approved' : 'rejected'
|
||||
const approvedAt = new Date()
|
||||
const updated = await tx.disposalRecord.updateMany({
|
||||
where: { id: disposalId, status: 'pending' },
|
||||
data: {
|
||||
status: nextStatus,
|
||||
approved_by: userId,
|
||||
approved_at: approvedAt,
|
||||
reject_reason: approved ? null : reject_reason?.trim()
|
||||
}
|
||||
})
|
||||
if (updated.count !== 1) {
|
||||
throw new DisposalConflictError('该申请已被其他人处理,请刷新后查看')
|
||||
}
|
||||
|
||||
if (!approved) {
|
||||
for (const item of disposal.items) {
|
||||
await updateEquipmentLifecycle(
|
||||
tx,
|
||||
item.equipment,
|
||||
item.pre_status,
|
||||
'待报废',
|
||||
item.parent_equipment_id
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
await tx.disposalAction.create({
|
||||
data: {
|
||||
disposal_id: disposalId,
|
||||
action_type: approved ? 'approved' : 'rejected',
|
||||
operator_id: userId,
|
||||
from_status: 'pending',
|
||||
to_status: nextStatus,
|
||||
detail: approved ? null : reject_reason?.trim()
|
||||
}
|
||||
})
|
||||
await writeDisposalDecision(tx, disposal, decision, userId, approvedAt, confirmation)
|
||||
|
||||
const recipients = await getResultRecipients(tx, disposal.applied_by)
|
||||
const rootItem = disposal.items.find((item) => item.equipment_id === disposal.equipment_id)
|
||||
@ -880,7 +904,7 @@ export const approveDisposal = async (req: Request, res: Response) => {
|
||||
businessType: 'disposal',
|
||||
businessId: disposal.id,
|
||||
title: approved ? `报废已审批:${disposal.equipment_code}` : `报废已驳回:${disposal.equipment_code}`,
|
||||
content: approved ? '报废申请已审批通过,等待完成处置' : `驳回原因:${reject_reason?.trim()}`,
|
||||
content: approved ? '报废申请已审批通过,等待完成处置' : `驳回原因:${rejectReason}`,
|
||||
level: approved ? 'success' : 'warning',
|
||||
actionUrl: `/workflows/disposals/${disposal.id}`,
|
||||
stationRecipients: recipients.stationRecipients,
|
||||
@ -904,7 +928,7 @@ export const approveDisposal = async (req: Request, res: Response) => {
|
||||
equipmentName: rootItem?.equipment.equipment_name,
|
||||
equipmentCode: disposal.equipment_code,
|
||||
rejectorName: res.locals.user?.name || res.locals.user?.username,
|
||||
reason: reject_reason
|
||||
reason: rejectReason
|
||||
}),
|
||||
actionTitle: '查看申请',
|
||||
messageVersion: 'v1'
|
||||
@ -913,11 +937,12 @@ export const approveDisposal = async (req: Request, res: Response) => {
|
||||
return disposal
|
||||
}, { isolationLevel: Prisma.TransactionIsolationLevel.ReadCommitted })
|
||||
|
||||
const operation = getDisposalDecisionOperation(result, approved)
|
||||
await logOperation(
|
||||
userId,
|
||||
res.locals.user?.username || res.locals.user?.name || 'unknown',
|
||||
approved ? '报废审批通过' : '报废审批驳回',
|
||||
`${approved ? '批准' : '驳回'}资产 ${result.equipment_code} 的报废申请`,
|
||||
operation.operation_type,
|
||||
operation.operation_details,
|
||||
result.equipment_id,
|
||||
result.equipment_code,
|
||||
req.ip
|
||||
@ -928,6 +953,139 @@ export const approveDisposal = async (req: Request, res: Response) => {
|
||||
}
|
||||
}
|
||||
|
||||
const throwBatchDisposalConflict = (equipmentCode: string, error: unknown): never => {
|
||||
if (error instanceof DisposalConflictError) {
|
||||
throw new DisposalConflictError(`${equipmentCode}:${error.message}`)
|
||||
}
|
||||
throw error
|
||||
}
|
||||
|
||||
const loadLockedBatchDisposalDecisions = async (tx: Prisma.TransactionClient, disposalIds: number[]) => {
|
||||
const initial = await tx.disposalRecord.findMany({
|
||||
where: { id: { in: disposalIds } },
|
||||
select: { id: true, equipment_id: true, equipment_code: true, items: { select: { equipment_id: true } } }
|
||||
})
|
||||
const initialById = new Map(initial.map(disposal => [disposal.id, disposal]))
|
||||
const equipmentIdsByDisposal = new Map<number, Set<number>>()
|
||||
const equipmentIds = new Set<number>()
|
||||
for (const id of disposalIds) {
|
||||
const disposal = initialById.get(id)
|
||||
if (!disposal) throw new DisposalConflictError(`报废单 ${id} 不存在,请刷新列表`)
|
||||
const ids = new Set([disposal.equipment_id, ...disposal.items.map(item => item.equipment_id)])
|
||||
for (const equipmentId of ids) {
|
||||
if (equipmentIds.has(equipmentId)) {
|
||||
throw new DisposalConflictError(`${disposal.equipment_code}:本批报废单的资产范围重叠,请逐单核查`)
|
||||
}
|
||||
equipmentIds.add(equipmentId)
|
||||
}
|
||||
equipmentIdsByDisposal.set(id, ids)
|
||||
}
|
||||
await lockEquipmentRows(tx, [...equipmentIds])
|
||||
|
||||
const current = await tx.disposalRecord.findMany({
|
||||
where: { id: { in: disposalIds } }, include: disposalDecisionInclude
|
||||
})
|
||||
const currentById = new Map(current.map(disposal => [disposal.id, disposal]))
|
||||
const decisions = disposalIds.map(id => {
|
||||
const disposal = currentById.get(id)
|
||||
const equipmentCode = initialById.get(id)!.equipment_code
|
||||
if (!disposal) throw new DisposalConflictError(`${equipmentCode}:报废单已移除,请刷新列表`)
|
||||
try {
|
||||
const root = getDisposalDecisionRoot(disposal, 'pending', equipmentIdsByDisposal.get(id)!)
|
||||
return { disposal, root }
|
||||
} catch (error) {
|
||||
return throwBatchDisposalConflict(equipmentCode, error)
|
||||
}
|
||||
})
|
||||
const trees = await loadDisposalTrees(tx, decisions.map(({ root }) => root))
|
||||
return decisions.map(({ disposal, root }) => {
|
||||
try {
|
||||
assertDisposalDecisionTree(disposal, trees.get(root.id)!)
|
||||
return disposal
|
||||
} catch (error) {
|
||||
return throwBatchDisposalConflict(disposal.equipment_code, error)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
const notifyBatchDisposalDecisions = async (
|
||||
tx: Prisma.TransactionClient,
|
||||
disposals: DisposalDecisionRecord[],
|
||||
{ approved, rejectReason }: DisposalDecision,
|
||||
operatorName: string,
|
||||
decidedAt: Date
|
||||
) => {
|
||||
const byApplicant = new Map<number, DisposalDecisionRecord[]>()
|
||||
for (const disposal of disposals) {
|
||||
const group = byApplicant.get(disposal.applied_by)
|
||||
if (group) group.push(disposal)
|
||||
else byApplicant.set(disposal.applied_by, [disposal])
|
||||
}
|
||||
const statusText = approved ? '已通过' : '已驳回'
|
||||
for (const [applicantId, group] of byApplicant) {
|
||||
const codes = group.map(disposal => disposal.equipment_code)
|
||||
const summary = codes.slice(0, 10).join('、') + (codes.length > 10 ? ` 等 ${codes.length} 个` : '')
|
||||
const recipients = await getResultRecipients(tx, applicantId)
|
||||
const title = `报废批量审批${statusText}:${group.length} 笔`
|
||||
await createBusinessNotification(tx, {
|
||||
...recipients,
|
||||
eventType: approved ? 'disposal_approved' : 'disposal_rejected',
|
||||
businessType: 'disposal',
|
||||
businessId: group[0].id,
|
||||
title,
|
||||
content: `${group.length} 笔报废申请${statusText}(${summary})${approved ? ',等待处置' : `。驳回原因:${rejectReason}`}`,
|
||||
level: approved ? 'success' : 'warning',
|
||||
actionUrl: group.length === 1 ? `/workflows/disposals/${group[0].id}` : '/workflows/disposals?scope=processed',
|
||||
metadata: { disposal_ids: group.map(disposal => disposal.id), equipment_codes: codes, count: group.length },
|
||||
dingTalk: {
|
||||
title, actionTitle: '查看审批结果', messageVersion: 'v1',
|
||||
content: [
|
||||
`**审批时间:** ${formatBeijingDateTime(decidedAt)}`,
|
||||
`**审批人:** ${escapeNotificationMarkdownInline(operatorName)}`,
|
||||
`**审批结果:** ${group.length} 笔${statusText}(${escapeNotificationMarkdownInline(summary)})`,
|
||||
approved ? '> 报废单现已进入待处置阶段。' : `**驳回原因:** ${escapeNotificationMarkdownInline(rejectReason)}`
|
||||
].join('\n\n')
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
export const approveBatchDisposal = async (req: Request, res: Response) => {
|
||||
try {
|
||||
const { id: userId } = getCurrentUser(res)
|
||||
if (!isEquipmentId(userId)) return errorResponse(res, '用户未登录', 401)
|
||||
const body = req.body || {}
|
||||
const disposalIds = body.disposal_ids
|
||||
if (!Array.isArray(disposalIds) || disposalIds.length < 1 || disposalIds.length > MAX_DISPOSAL_BATCH_ROOTS ||
|
||||
!disposalIds.every(isEquipmentId) || new Set(disposalIds).size !== disposalIds.length) {
|
||||
return errorResponse(res, `每批须提供 1 至 ${MAX_DISPOSAL_BATCH_ROOTS} 个不重复的有效报废单 ID`, 422)
|
||||
}
|
||||
const decision = readDisposalDecision(body)
|
||||
const operator = res.locals.user
|
||||
const operatorName = operator?.name || operator?.username || 'unknown'
|
||||
await prisma.$transaction(async tx => {
|
||||
const disposals = await loadLockedBatchDisposalDecisions(tx, disposalIds)
|
||||
const decidedAt = new Date()
|
||||
for (const disposal of disposals) {
|
||||
try {
|
||||
await writeDisposalDecision(tx, disposal, decision, userId, decidedAt)
|
||||
} catch (error) {
|
||||
throwBatchDisposalConflict(disposal.equipment_code, error)
|
||||
}
|
||||
}
|
||||
await tx.operationLog.createMany({ data: disposals.map(disposal => ({
|
||||
...getDisposalDecisionOperation(disposal, decision.approved),
|
||||
user_id: userId, username: operator?.username || operatorName,
|
||||
equipment_id: disposal.equipment_id, equipment_code: disposal.equipment_code, ip_address: req.ip || null
|
||||
})) })
|
||||
await notifyBatchDisposalDecisions(tx, disposals, decision, operatorName, decidedAt)
|
||||
}, { isolationLevel: Prisma.TransactionIsolationLevel.ReadCommitted, timeout: 30000 })
|
||||
successResponse(res, { count: disposalIds.length, disposal_ids: disposalIds }, decision.approved ? '批量审批通过' : '批量驳回成功')
|
||||
} catch (error: any) {
|
||||
errorResponse(res, error.message || '批量审批失败', error.status || 500)
|
||||
}
|
||||
}
|
||||
|
||||
export const completeDisposal = async (req: Request, res: Response) => {
|
||||
try {
|
||||
const disposalId = Number(req.params.id)
|
||||
|
||||
@ -6,6 +6,7 @@ import {
|
||||
getDisposalList,
|
||||
getDisposalDetail,
|
||||
approveDisposal,
|
||||
approveBatchDisposal,
|
||||
completeDisposal,
|
||||
getEquipmentDisposalHistory
|
||||
} from '../controllers/disposalController'
|
||||
@ -27,6 +28,7 @@ router.post(
|
||||
)
|
||||
router.get('/equipment/:equipment_id/history', requirePermission(PERMISSIONS.ASSETS_VIEW_ALL), getEquipmentDisposalHistory)
|
||||
router.get('/:id', requirePermission(PERMISSIONS.NOTIFICATIONS_VIEW), getDisposalDetail)
|
||||
router.put('/batch/approve', requirePermission(PERMISSIONS.DISPOSALS_APPROVE), approveBatchDisposal)
|
||||
router.put('/:id/approve', requirePermission(PERMISSIONS.DISPOSALS_APPROVE), approveDisposal)
|
||||
router.put('/:id/complete', requirePermission(PERMISSIONS.DISPOSALS_COMPLETE), completeDisposal)
|
||||
|
||||
|
||||
@ -193,6 +193,14 @@ export const approveDisposal = (id: number, data: {
|
||||
}) =>
|
||||
request.put(`/disposal/${id}/approve`, data)
|
||||
|
||||
export const approveBatchDisposal = (data: {
|
||||
disposal_ids: number[]
|
||||
approved: boolean
|
||||
reject_reason?: string
|
||||
}) => request
|
||||
.put<ApiResponse<{ count: number; disposal_ids: number[] }>>('/disposal/batch/approve', data, { timeout: 60000 })
|
||||
.then((response) => response.data)
|
||||
|
||||
export const completeDisposal = (id: number, data: { actual_value?: number; completion_notes?: string }) =>
|
||||
request.put(`/disposal/${id}/complete`, data)
|
||||
|
||||
|
||||
121
frontend/src/components/BatchDisposalApprovalDialog.vue
Normal file
121
frontend/src/components/BatchDisposalApprovalDialog.vue
Normal file
@ -0,0 +1,121 @@
|
||||
<template>
|
||||
<dialog
|
||||
ref="dialogElement"
|
||||
class="sheet-backdrop batch-approval-dialog"
|
||||
aria-labelledby="batch-approval-title"
|
||||
@click.self="close"
|
||||
@cancel.prevent="close"
|
||||
@keydown.tab="keepDialogTabFocus"
|
||||
>
|
||||
<div class="sheet-panel flex max-w-lg flex-col gap-4 overflow-hidden">
|
||||
<header class="shrink-0">
|
||||
<h3 id="batch-approval-title" ref="heading" class="section-title" tabindex="-1">批量审批</h3>
|
||||
<p class="mt-2 text-sm text-text-secondary">共 {{ records.length }} 项报废申请</p>
|
||||
</header>
|
||||
|
||||
<div class="min-h-0 space-y-4 overflow-y-auto overscroll-contain" role="region" aria-label="审批内容" tabindex="0">
|
||||
<ul class="grid gap-x-4 border-t border-border sm:grid-cols-2" aria-label="本次审批的资产编码">
|
||||
<li v-for="record in records" :key="record.id" class="flex justify-between gap-3 border-b border-border px-2 py-1.5 text-sm">
|
||||
<span class="min-w-0 break-all font-mono text-text-primary">{{ record.equipment_code }}</span>
|
||||
<span class="shrink-0 text-text-secondary">#{{ record.id }}</span>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
<fieldset class="min-w-0 space-y-2" :disabled="submitting">
|
||||
<legend class="field-label">审批结果</legend>
|
||||
<div class="flex flex-wrap gap-4">
|
||||
<label class="flex min-h-11 cursor-pointer items-center gap-2 text-sm text-text-primary">
|
||||
<input v-model="approved" type="radio" :value="true" name="batch-disposal-decision" class="border-border-hover bg-bg-elevated text-accent-primary focus:ring-accent-primary focus:ring-offset-bg-secondary">
|
||||
通过
|
||||
</label>
|
||||
<label class="flex min-h-11 cursor-pointer items-center gap-2 text-sm text-text-primary">
|
||||
<input v-model="approved" type="radio" :value="false" name="batch-disposal-decision" class="border-border-hover bg-bg-elevated text-accent-primary focus:ring-accent-primary focus:ring-offset-bg-secondary">
|
||||
驳回
|
||||
</label>
|
||||
</div>
|
||||
<div v-if="!approved" class="field-stack">
|
||||
<label for="batch-approval-reason" class="field-label">驳回原因 *</label>
|
||||
<textarea id="batch-approval-reason" v-model="rejectReason" class="input" rows="2" required></textarea>
|
||||
</div>
|
||||
</fieldset>
|
||||
<p v-if="errorMessage" ref="errorElement" class="break-words text-sm text-status-error" role="alert" tabindex="-1">{{ errorMessage }}</p>
|
||||
</div>
|
||||
|
||||
<footer class="flex shrink-0 flex-wrap justify-end gap-2 border-t border-border pt-4">
|
||||
<button type="button" class="btn-secondary" :disabled="submitting" @click="close">取消</button>
|
||||
<button type="button" class="btn-primary" :disabled="!canSubmit" :aria-busy="submitting" @click="submit">
|
||||
{{ submitting ? '正在提交…' : approved ? '提交通过' : '提交驳回' }}
|
||||
</button>
|
||||
</footer>
|
||||
</div>
|
||||
</dialog>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onMounted, ref } from 'vue'
|
||||
import { approveBatchDisposal } from '@/api/disposal'
|
||||
import { keepDialogTabFocus } from '@/utils/dialogFocus'
|
||||
|
||||
const props = defineProps<{ records: Array<{ id: number; equipment_code: string }> }>()
|
||||
const emit = defineEmits<{ close: []; completed: [result: { count: number; approved: boolean }] }>()
|
||||
const dialogElement = ref<HTMLDialogElement | null>(null)
|
||||
const heading = ref<HTMLElement | null>(null)
|
||||
const errorElement = ref<HTMLElement | null>(null)
|
||||
const approved = ref(true)
|
||||
const rejectReason = ref('')
|
||||
const submitting = ref(false)
|
||||
const errorMessage = ref('')
|
||||
const canSubmit = computed(() => props.records.length > 0 && !submitting.value && (approved.value || Boolean(rejectReason.value.trim())))
|
||||
|
||||
const close = () => {
|
||||
if (submitting.value) return
|
||||
dialogElement.value?.close()
|
||||
emit('close')
|
||||
}
|
||||
|
||||
const submit = async () => {
|
||||
if (!canSubmit.value) return
|
||||
const decision = approved.value
|
||||
submitting.value = true
|
||||
errorMessage.value = ''
|
||||
try {
|
||||
const response = await approveBatchDisposal({
|
||||
disposal_ids: props.records.map((record) => record.id),
|
||||
approved: decision,
|
||||
...(decision ? {} : { reject_reason: rejectReason.value.trim() })
|
||||
})
|
||||
if (!response.data) throw new Error('未收到审批结果,请核对报废记录')
|
||||
dialogElement.value?.close()
|
||||
emit('completed', { count: response.data.count, approved: decision })
|
||||
} catch (error) {
|
||||
errorMessage.value = error instanceof Error ? error.message : '批量审批失败,请稍后重试'
|
||||
void nextTick(() => errorElement.value?.focus())
|
||||
} finally {
|
||||
submitting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
dialogElement.value?.showModal()
|
||||
heading.value?.focus({ preventScroll: true })
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.batch-approval-dialog {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
max-width: none;
|
||||
max-height: none;
|
||||
margin: 0;
|
||||
color: inherit;
|
||||
}
|
||||
|
||||
.batch-approval-dialog:not([open]) {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.batch-approval-dialog::backdrop {
|
||||
background: transparent;
|
||||
}
|
||||
</style>
|
||||
@ -91,13 +91,25 @@
|
||||
<h3 class="section-title">报废记录</h3>
|
||||
<p class="mt-1 text-xs text-text-tertiary">当前范围共 {{ summary?.total || 0 }} 条,筛选结果 {{ total }} 条</p>
|
||||
</div>
|
||||
<button class="btn-secondary text-xs sm:text-sm" :disabled="loading" @click="loadList">刷新</button>
|
||||
<div class="flex flex-wrap items-center gap-2 sm:justify-end">
|
||||
<template v-if="canBatchApprove">
|
||||
<p class="whitespace-nowrap text-xs tabular-nums text-text-secondary" role="status">已选 {{ selectedRecords.size }} 项</p>
|
||||
<button type="button" class="btn-secondary text-xs sm:text-sm" aria-label="全选筛选结果" :aria-busy="selectingAll" :disabled="!selectionReady || !total" @click="selectAllFiltered">
|
||||
{{ selectingAll ? '正在全选…' : '全选' }}
|
||||
</button>
|
||||
<button v-if="selectedRecords.size" type="button" class="btn-secondary text-xs sm:text-sm" :disabled="selectingAll" @click="clearSelection">清空</button>
|
||||
<button type="button" class="btn-primary text-xs sm:text-sm" :disabled="!selectionReady || !selectedRecords.size" @click="openBatchApproval">批量审批</button>
|
||||
</template>
|
||||
<button class="btn-secondary text-xs sm:text-sm" :disabled="loading" @click="refreshList">刷新</button>
|
||||
</div>
|
||||
</div>
|
||||
<p v-if="selectionError" class="mb-3 break-words text-sm text-status-error" role="alert">{{ selectionError }}</p>
|
||||
<p v-if="batchNotice" class="mb-3 text-sm text-status-success" role="status">{{ batchNotice }}</p>
|
||||
|
||||
<div v-if="loading" class="empty-state">正在加载报废记录...</div>
|
||||
<div v-else-if="listError" class="panel flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
|
||||
<p class="text-sm text-status-error">{{ listError }}</p>
|
||||
<button class="btn-secondary" @click="loadList">重新加载</button>
|
||||
<button class="btn-secondary" @click="refreshList">重新加载</button>
|
||||
</div>
|
||||
|
||||
<template v-else>
|
||||
@ -106,9 +118,21 @@
|
||||
<div class="mobile-card-list md:hidden">
|
||||
<article v-for="item in list" :key="`mobile-${item.id}`" class="mobile-card">
|
||||
<div class="mobile-card__row">
|
||||
<div>
|
||||
<p class="text-sm font-semibold text-text-primary">{{ item.equipment?.equipment_name || '-' }}</p>
|
||||
<p class="mt-1 text-xs font-mono text-text-tertiary">{{ item.equipment_code }}</p>
|
||||
<div class="flex min-w-0 items-center gap-2">
|
||||
<label v-if="canBatchApprove && item.status === 'pending'" class="flex h-9 w-8 shrink-0 cursor-pointer items-center justify-center">
|
||||
<input
|
||||
type="checkbox"
|
||||
:aria-label="`选择 ${item.equipment_code} 报废申请 #${item.id}`"
|
||||
:checked="selectedRecords.has(item.id)"
|
||||
:disabled="!selectionReady"
|
||||
class="rounded border-border-hover bg-bg-elevated text-accent-primary focus:ring-accent-primary focus:ring-offset-bg-secondary"
|
||||
@change="toggleSelection(item, $event)"
|
||||
>
|
||||
</label>
|
||||
<div class="min-w-0 break-words">
|
||||
<p class="text-sm font-semibold text-text-primary">{{ item.equipment?.equipment_name || '-' }}</p>
|
||||
<p class="mt-1 text-xs font-mono text-text-tertiary">{{ item.equipment_code }}</p>
|
||||
</div>
|
||||
</div>
|
||||
<span class="badge" :class="getStatusBadgeClass(item.status)">
|
||||
{{ getStatusText(item.status) }}
|
||||
@ -181,6 +205,7 @@
|
||||
<table class="data-table min-w-[1080px]">
|
||||
<thead>
|
||||
<tr>
|
||||
<th v-if="canBatchApprove" class="w-10"><span class="sr-only">选择</span></th>
|
||||
<th>资产编码</th>
|
||||
<th>资产名称</th>
|
||||
<th>报废原因</th>
|
||||
@ -194,6 +219,18 @@
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="item in list" :key="item.id">
|
||||
<td v-if="canBatchApprove">
|
||||
<label v-if="item.status === 'pending'" class="flex h-9 w-7 cursor-pointer items-center justify-center">
|
||||
<input
|
||||
type="checkbox"
|
||||
:aria-label="`选择 ${item.equipment_code} 报废申请 #${item.id}`"
|
||||
:checked="selectedRecords.has(item.id)"
|
||||
:disabled="!selectionReady"
|
||||
class="rounded border-border-hover bg-bg-elevated text-accent-primary focus:ring-accent-primary focus:ring-offset-bg-secondary"
|
||||
@change="toggleSelection(item, $event)"
|
||||
>
|
||||
</label>
|
||||
</td>
|
||||
<td class="font-mono text-sm text-text-secondary">{{ item.equipment_code }}</td>
|
||||
<td>
|
||||
<p class="font-medium text-text-primary">{{ item.equipment?.equipment_name || '-' }}</p>
|
||||
@ -241,7 +278,7 @@
|
||||
</td>
|
||||
</tr>
|
||||
<tr v-if="!loading && list.length === 0">
|
||||
<td colspan="9" class="py-8 text-center text-text-tertiary">当前筛选条件下暂无报废记录。</td>
|
||||
<td :colspan="canBatchApprove ? 10 : 9" class="py-8 text-center text-text-tertiary">当前筛选条件下暂无报废记录。</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
@ -252,8 +289,8 @@
|
||||
<div class="pagination-bar">
|
||||
<p class="text-sm text-text-secondary">第 {{ page }} / {{ totalPages }} 页</p>
|
||||
<div class="flex items-center gap-2">
|
||||
<button class="btn-secondary text-sm" :disabled="page <= 1 || loading" @click="handlePrevPage">上一页</button>
|
||||
<button class="btn-secondary text-sm" :disabled="page >= totalPages || loading" @click="handleNextPage">下一页</button>
|
||||
<button class="btn-secondary text-sm" :disabled="page <= 1 || !paginationReady" @click="handlePrevPage">上一页</button>
|
||||
<button class="btn-secondary text-sm" :disabled="page >= totalPages || !paginationReady" @click="handleNextPage">下一页</button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@ -276,11 +313,18 @@
|
||||
</button>
|
||||
</MobileActionSheet>
|
||||
|
||||
<BatchDisposalApprovalDialog
|
||||
v-if="canBatchApprove && reviewRecords"
|
||||
:records="reviewRecords"
|
||||
@close="reviewRecords = null"
|
||||
@completed="handleBatchCompleted"
|
||||
/>
|
||||
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
|
||||
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import {
|
||||
getDisposalList,
|
||||
@ -291,9 +335,13 @@ import {
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
import { PERMISSIONS } from '@/auth/permissions'
|
||||
import MobileActionSheet from '@/components/MobileActionSheet.vue'
|
||||
import BatchDisposalApprovalDialog from '@/components/BatchDisposalApprovalDialog.vue'
|
||||
import { createRequestScope } from '@/utils/requestScope'
|
||||
|
||||
type DisposalScope = 'pending' | 'mine' | 'processed' | 'all'
|
||||
type DisposalQuery = { scope: DisposalScope; status: string; keyword: string }
|
||||
type ApprovalSelection = Pick<DisposalRecord, 'id' | 'equipment_code'>
|
||||
const maxBatchApprovalCount = 500
|
||||
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
@ -321,35 +369,83 @@ const summary = ref<DisposalSummary | null>(null)
|
||||
const filters = ref({ status: '', keyword: '' })
|
||||
const activeScope = ref<DisposalScope>('pending')
|
||||
const mobileActionItem = ref<DisposalRecord | null>(null)
|
||||
const appliedQuery = ref<DisposalQuery | null>(null)
|
||||
const selectedRecords = ref(new Map<number, ApprovalSelection>())
|
||||
const selectingAll = ref(false)
|
||||
const selectionError = ref('')
|
||||
const batchNotice = ref('')
|
||||
const reviewRecords = ref<ApprovalSelection[] | null>(null)
|
||||
|
||||
let searchTimer: ReturnType<typeof setTimeout> | null = null
|
||||
const listScope = createRequestScope()
|
||||
const selectAllScope = createRequestScope()
|
||||
const draftQuery = computed(() => ({ scope: activeScope.value, status: filters.value.status, keyword: filters.value.keyword.trim() }))
|
||||
const sameQuery = (left: DisposalQuery, right: DisposalQuery | null) =>
|
||||
Boolean(right && left.scope === right.scope && left.status === right.status && left.keyword === right.keyword)
|
||||
const canBatchApprove = computed(() => canApprove.value && activeScope.value === 'pending')
|
||||
const paginationReady = computed(() => !loading.value && !selectingAll.value && sameQuery(draftQuery.value, appliedQuery.value))
|
||||
const selectionReady = computed(() => canBatchApprove.value && paginationReady.value && !listError.value)
|
||||
|
||||
const cancelSelectAll = () => {
|
||||
selectAllScope.begin()
|
||||
selectingAll.value = false
|
||||
}
|
||||
|
||||
const clearSelection = () => {
|
||||
cancelSelectAll()
|
||||
selectedRecords.value.clear()
|
||||
selectionError.value = ''
|
||||
}
|
||||
|
||||
watch([draftQuery, canApprove], () => {
|
||||
clearSelection()
|
||||
reviewRecords.value = null
|
||||
batchNotice.value = ''
|
||||
}, { flush: 'sync' })
|
||||
|
||||
const stopSearchTimer = () => {
|
||||
if (searchTimer) clearTimeout(searchTimer)
|
||||
searchTimer = null
|
||||
}
|
||||
|
||||
const totalPages = computed(() => Math.max(1, Math.ceil(total.value / pageSize.value)))
|
||||
const loadList = async () => {
|
||||
stopSearchTimer()
|
||||
cancelSelectAll()
|
||||
const request = listScope.begin()
|
||||
const query = draftQuery.value
|
||||
if (!sameQuery(query, appliedQuery.value)) page.value = 1
|
||||
loading.value = true
|
||||
listError.value = ''
|
||||
try {
|
||||
const res = await getDisposalList({ page: page.value, pageSize: pageSize.value, scope: activeScope.value, ...filters.value })
|
||||
if (!listScope.isCurrent(request)) return
|
||||
list.value = res.data?.list || []
|
||||
total.value = res.data?.total || 0
|
||||
summary.value = res.data?.summary || null
|
||||
const res = await getDisposalList({ page: page.value, pageSize: pageSize.value, ...query })
|
||||
if (!listScope.isCurrent(request) || !sameQuery(query, draftQuery.value)) return
|
||||
if (!res.data) throw new Error('未收到报废记录,请重新加载。')
|
||||
list.value = res.data.list
|
||||
total.value = res.data.total
|
||||
summary.value = res.data.summary
|
||||
appliedQuery.value = query
|
||||
} catch (e: any) {
|
||||
if (!listScope.isCurrent(request)) return
|
||||
if (!listScope.isCurrent(request) || !sameQuery(query, draftQuery.value)) return
|
||||
console.error(e)
|
||||
list.value = []
|
||||
total.value = 0
|
||||
summary.value = null
|
||||
appliedQuery.value = null
|
||||
listError.value = e?.message || '报废记录加载失败,请稍后重试。'
|
||||
} finally {
|
||||
if (listScope.isCurrent(request)) loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const refreshList = () => {
|
||||
clearSelection()
|
||||
batchNotice.value = ''
|
||||
return loadList()
|
||||
}
|
||||
|
||||
const handleSearch = () => {
|
||||
if (searchTimer) clearTimeout(searchTimer)
|
||||
stopSearchTimer()
|
||||
searchTimer = setTimeout(() => {
|
||||
page.value = 1
|
||||
loadList()
|
||||
@ -362,8 +458,7 @@ const handleQuery = () => {
|
||||
}
|
||||
|
||||
const resetFilters = () => {
|
||||
filters.value.status = ''
|
||||
filters.value.keyword = ''
|
||||
filters.value = { status: '', keyword: '' }
|
||||
handleQuery()
|
||||
}
|
||||
|
||||
@ -375,16 +470,78 @@ const changeScope = (scope: DisposalScope) => {
|
||||
}
|
||||
|
||||
const showOwnApplications = () => {
|
||||
if (searchTimer) {
|
||||
clearTimeout(searchTimer)
|
||||
searchTimer = null
|
||||
}
|
||||
filters.value = { status: '', keyword: '' }
|
||||
return changeScope('mine')
|
||||
}
|
||||
|
||||
defineExpose({ showOwnApplications })
|
||||
|
||||
const toggleSelection = (item: DisposalRecord, event: Event) => {
|
||||
const checkbox = event.currentTarget as HTMLInputElement
|
||||
const wasSelected = selectedRecords.value.has(item.id)
|
||||
if (!selectionReady.value || item.status !== 'pending') {
|
||||
checkbox.checked = wasSelected
|
||||
return
|
||||
}
|
||||
selectionError.value = ''
|
||||
batchNotice.value = ''
|
||||
if (!checkbox.checked) {
|
||||
selectedRecords.value.delete(item.id)
|
||||
} else if (!wasSelected && selectedRecords.value.size >= maxBatchApprovalCount) {
|
||||
checkbox.checked = false
|
||||
selectionError.value = `每批最多审批 ${maxBatchApprovalCount} 项。`
|
||||
} else {
|
||||
selectedRecords.value.set(item.id, { id: item.id, equipment_code: item.equipment_code })
|
||||
}
|
||||
}
|
||||
|
||||
const selectAllFiltered = async () => {
|
||||
const query = appliedQuery.value
|
||||
if (!selectionReady.value || !query || !total.value) return
|
||||
const expectedTotal = total.value
|
||||
selectionError.value = ''
|
||||
batchNotice.value = ''
|
||||
if (expectedTotal > maxBatchApprovalCount) {
|
||||
selectionError.value = `筛选结果超过 ${maxBatchApprovalCount} 项,请缩小范围或逐项勾选。`
|
||||
return
|
||||
}
|
||||
|
||||
const request = selectAllScope.begin()
|
||||
selectingAll.value = true
|
||||
const selection = new Map<number, ApprovalSelection>()
|
||||
const perPage = 100
|
||||
try {
|
||||
for (let current = 1; current <= Math.ceil(expectedTotal / perPage); current += 1) {
|
||||
const response = await getDisposalList({ ...query, page: current, pageSize: perPage })
|
||||
if (!selectAllScope.isCurrent(request)) return
|
||||
if (!response.data || response.data.total !== expectedTotal) throw new Error('筛选结果已变化,请刷新后再全选。')
|
||||
for (const item of response.data.list) {
|
||||
if (item.status === 'pending') selection.set(item.id, { id: item.id, equipment_code: item.equipment_code })
|
||||
}
|
||||
}
|
||||
if (selection.size !== expectedTotal) throw new Error('筛选结果已变化,请刷新后再全选。')
|
||||
selectedRecords.value = selection
|
||||
} catch (error) {
|
||||
if (selectAllScope.isCurrent(request)) selectionError.value = error instanceof Error ? error.message : '全选失败,请稍后重试。'
|
||||
} finally {
|
||||
if (selectAllScope.isCurrent(request)) selectingAll.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const openBatchApproval = () => {
|
||||
if (!selectionReady.value || !selectedRecords.value.size) return
|
||||
batchNotice.value = ''
|
||||
reviewRecords.value = [...selectedRecords.value.values()]
|
||||
}
|
||||
|
||||
const handleBatchCompleted = ({ count, approved }: { count: number; approved: boolean }) => {
|
||||
reviewRecords.value = null
|
||||
clearSelection()
|
||||
batchNotice.value = `已${approved ? '通过' : '驳回'} ${count} 项报废申请。`
|
||||
page.value = 1
|
||||
void loadList()
|
||||
}
|
||||
|
||||
const openDetail = (item: DisposalRecord) => router.push(`/workflows/disposals/${item.id}`)
|
||||
|
||||
const handleMobileOpenDetail = () => {
|
||||
@ -408,6 +565,7 @@ const handleReject = async (item: DisposalRecord) => {
|
||||
return
|
||||
}
|
||||
await approveDisposal(item.id, { approved: false, reject_reason: rejectReason })
|
||||
selectedRecords.value.delete(item.id)
|
||||
await loadList()
|
||||
} catch (error: any) {
|
||||
alert(error?.message || '申请状态已变化,请刷新后重试')
|
||||
@ -416,13 +574,13 @@ const handleReject = async (item: DisposalRecord) => {
|
||||
}
|
||||
|
||||
const handlePrevPage = async () => {
|
||||
if (page.value <= 1) return
|
||||
if (!paginationReady.value || page.value <= 1) return
|
||||
page.value -= 1
|
||||
await loadList()
|
||||
}
|
||||
|
||||
const handleNextPage = async () => {
|
||||
if (page.value >= totalPages.value) return
|
||||
if (!paginationReady.value || page.value >= totalPages.value) return
|
||||
page.value += 1
|
||||
await loadList()
|
||||
}
|
||||
@ -455,17 +613,30 @@ const formatDate = (date: string) => {
|
||||
const formatCurrency = (value: number) => `¥${Number(value || 0).toFixed(2)}`
|
||||
const formatSummaryCount = (value?: number) => loading.value && summary.value === null ? '—' : String(value || 0)
|
||||
|
||||
onMounted(() => {
|
||||
const resolveRouteScope = () => {
|
||||
const requestedScope = route.query.scope as DisposalScope | undefined
|
||||
const allowedScopes = availableScopes.value.map((scope) => scope.value)
|
||||
activeScope.value = requestedScope && allowedScopes.includes(requestedScope)
|
||||
return requestedScope && allowedScopes.includes(requestedScope)
|
||||
? requestedScope
|
||||
: allowedScopes[0] || 'mine'
|
||||
}
|
||||
|
||||
watch(() => route.query.scope, () => {
|
||||
const scope = resolveRouteScope()
|
||||
if (scope === activeScope.value) return
|
||||
activeScope.value = scope
|
||||
page.value = 1
|
||||
void loadList()
|
||||
})
|
||||
|
||||
onMounted(() => {
|
||||
activeScope.value = resolveRouteScope()
|
||||
loadList()
|
||||
})
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
if (searchTimer) clearTimeout(searchTimer)
|
||||
stopSearchTimer()
|
||||
listScope.dispose()
|
||||
selectAllScope.dispose()
|
||||
})
|
||||
</script>
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user