Fix disposal returns and approval state transitions
This commit is contained in:
parent
2d83bc8b4d
commit
d344e331fd
@ -73,9 +73,15 @@ test('资产数量、报废和盘点的本机 MySQL 回归', {
|
||||
call(updateEquipment, operator, { total_quantity, description }, { id: String(row.id) })
|
||||
const borrow = (row: Equipment, personId: number) =>
|
||||
call(borrowEquipment, operator, { equipment_id: row.id, person_id: personId, is_long_term: true })
|
||||
const submit = (row: Equipment, item_ids = [row.id]) => call(createDisposal, operator, {
|
||||
equipment_id: row.id, item_ids, disposal_reason: '设备老化', disposal_method: '报废'
|
||||
})
|
||||
const submit = async (row: Equipment, item_ids = [row.id], confirmed_quantities?: { equipment_id: number; total_quantity: number }[]) => {
|
||||
const quantities = confirmed_quantities ?? (await prisma.equipment.findMany({
|
||||
where: { id: { in: item_ids } }, select: { id: true, total_quantity: true }
|
||||
})).map(item => ({ equipment_id: item.id, total_quantity: item.total_quantity }))
|
||||
return call(createDisposal, operator, {
|
||||
equipment_id: row.id, item_ids, disposal_reason: '设备老化', disposal_method: '报废',
|
||||
confirmed_quantities: quantities
|
||||
})
|
||||
}
|
||||
const approve = (id: number, extra = {}, user = reviewer) =>
|
||||
call(approveDisposal, user, { approved: true, ...extra }, { id: String(id) })
|
||||
const complete = (id: number) => call(completeDisposal, operator, {}, { id: String(id) })
|
||||
@ -128,6 +134,17 @@ test('资产数量、报废和盘点的本机 MySQL 回归', {
|
||||
await t.test('审批冻结整棵树的数量,数量纠错和完成均检查冻结值', async () => {
|
||||
const root = await asset('disposal-root', 2)
|
||||
const child = await asset('disposal-child', 1, root.id)
|
||||
const missing = await call(createDisposal, operator, {
|
||||
equipment_id: root.id, item_ids: [root.id, child.id], disposal_reason: '设备老化', disposal_method: '报废'
|
||||
})
|
||||
assert.equal(missing.status, 422)
|
||||
assert.match(missing.body.message, /缺少报废数量确认.*刷新页面/)
|
||||
const stale = await submit(root, [root.id, child.id], [
|
||||
{ equipment_id: root.id, total_quantity: 1 }, { equipment_id: child.id, total_quantity: 1 }
|
||||
])
|
||||
assert.equal(stale.status, 409)
|
||||
assert.match(stale.body.message, /与本次确认不一致/)
|
||||
assert.equal((await equipmentState(root)).status, '可用')
|
||||
const created = await submit(root, [root.id, child.id])
|
||||
assert.equal(created.status, 200, JSON.stringify(created.body))
|
||||
const id = created.body.data.id
|
||||
|
||||
@ -203,6 +203,7 @@ test('行政可在报废前将唯一未归还资产快捷入库,并保留正
|
||||
equipment_id: borrowedRoot.id,
|
||||
person_id: 15,
|
||||
status: '已借出',
|
||||
return_time: null,
|
||||
children_snapshot: null,
|
||||
updated_at: now
|
||||
}
|
||||
@ -259,10 +260,20 @@ test('行政可在报废前将唯一未归还资产快捷入库,并保留正
|
||||
}
|
||||
|
||||
try {
|
||||
await returnEquipmentBeforeDisposal({
|
||||
params: { equipment_id: String(borrowedRoot.id) }, body: { borrow_record_id: borrowRecord.id - 1, return_condition: '损坏' }
|
||||
} as any, res as any)
|
||||
assert.equal(state.statusCode, 409)
|
||||
assert.match(state.body.message, /借用单已变化/)
|
||||
assert.equal(rootUpdates.length, 0)
|
||||
assert.equal(movementReasons.length, 0)
|
||||
assert.equal(borrowRecord.status, '已借出')
|
||||
|
||||
state.statusCode = 200
|
||||
await returnEquipmentBeforeDisposal(
|
||||
{
|
||||
params: { equipment_id: String(borrowedRoot.id) },
|
||||
body: { return_condition: '损坏' }
|
||||
body: { borrow_record_id: borrowRecord.id, return_condition: '损坏' }
|
||||
} as any,
|
||||
res as any
|
||||
)
|
||||
@ -279,12 +290,12 @@ test('行政可在报废前将唯一未归还资产快捷入库,并保留正
|
||||
}
|
||||
})
|
||||
|
||||
test('报废前快捷入库遇到多条未归还记录时拒绝自动处理', async () => {
|
||||
test('报废前快捷入库遇到多条或没有未归还记录时返回 409', async () => {
|
||||
const originalTransaction = prisma.$transaction
|
||||
const borrowedRoot = { ...root, status: '已借出', total_quantity: 1, remaining_quantity: 0 }
|
||||
let transactionCount = 0
|
||||
let businessWriteCount = 0
|
||||
const activeRecords = [
|
||||
let activeRecords = [
|
||||
{ id: 701, equipment_id: root.id, person_id: 1, status: '已借出', children_snapshot: null, updated_at: now },
|
||||
{ id: 702, equipment_id: root.id, person_id: 2, status: '已借出', children_snapshot: null, updated_at: now }
|
||||
]
|
||||
@ -331,13 +342,20 @@ test('报废前快捷入库遇到多条未归还记录时拒绝自动处理', as
|
||||
|
||||
try {
|
||||
await returnEquipmentBeforeDisposal(
|
||||
{ params: { equipment_id: String(root.id) }, body: {} } as any,
|
||||
{ params: { equipment_id: String(root.id) }, body: { borrow_record_id: 701 } } as any,
|
||||
res as any
|
||||
)
|
||||
|
||||
assert.equal(state.statusCode, 422)
|
||||
assert.equal(state.statusCode, 409)
|
||||
assert.match(state.body.message, /多条未归还记录/)
|
||||
assert.equal(transactionCount, 1)
|
||||
activeRecords = []
|
||||
await returnEquipmentBeforeDisposal(
|
||||
{ params: { equipment_id: String(root.id) }, body: { borrow_record_id: 701 } } as any,
|
||||
res as any
|
||||
)
|
||||
assert.equal(state.statusCode, 409)
|
||||
assert.match(state.body.message, /没有对应的未归还记录.*刷新页面/)
|
||||
assert.equal(transactionCount, 2)
|
||||
assert.equal(businessWriteCount, 0)
|
||||
} finally {
|
||||
;(prisma.$transaction as any) = originalTransaction
|
||||
@ -393,7 +411,13 @@ test('报废前快捷入库拒绝未收回或多数量资产,且不会产生
|
||||
|
||||
try {
|
||||
await returnEquipmentBeforeDisposal(
|
||||
{ params: { equipment_id: String(root.id) }, body: { return_condition: '丢失' } } as any,
|
||||
{ params: { equipment_id: String(root.id) }, body: {} } as any, res as any
|
||||
)
|
||||
assert.equal(state.statusCode, 422)
|
||||
assert.match(state.body.message, /缺少有效借用单.*刷新页面/)
|
||||
|
||||
await returnEquipmentBeforeDisposal(
|
||||
{ params: { equipment_id: String(root.id) }, body: { borrow_record_id: 701, return_condition: '丢失' } } as any,
|
||||
res as any
|
||||
)
|
||||
assert.equal(state.statusCode, 422)
|
||||
@ -403,10 +427,10 @@ test('报废前快捷入库拒绝未收回或多数量资产,且不会产生
|
||||
state.body = null
|
||||
|
||||
await returnEquipmentBeforeDisposal(
|
||||
{ params: { equipment_id: String(root.id) }, body: { return_condition: '正常' } } as any,
|
||||
{ params: { equipment_id: String(root.id) }, body: { borrow_record_id: 701, return_condition: '正常' } } as any,
|
||||
res as any
|
||||
)
|
||||
assert.equal(state.statusCode, 422)
|
||||
assert.equal(state.statusCode, 409)
|
||||
assert.match(state.body.message, /仅支持单件资产/)
|
||||
assert.equal(transactionCount, 1)
|
||||
assert.equal(businessWriteCount, 0)
|
||||
@ -423,6 +447,7 @@ test('借出时无配件但当前新增配件时进入版本确认,配件再
|
||||
id: 803,
|
||||
equipment_id: borrowedRoot.id,
|
||||
person_id: 15,
|
||||
return_time: null,
|
||||
children_snapshot: null,
|
||||
updated_at: now
|
||||
}
|
||||
@ -470,7 +495,7 @@ test('借出时无配件但当前新增配件时进入版本确认,配件再
|
||||
|
||||
try {
|
||||
await returnEquipmentBeforeDisposal(
|
||||
{ params: { equipment_id: String(root.id) }, body: { return_condition: '正常' } } as any,
|
||||
{ params: { equipment_id: String(root.id) }, body: { borrow_record_id: borrowRecord.id, return_condition: '正常' } } as any,
|
||||
res as any
|
||||
)
|
||||
assert.equal(state.statusCode, 200)
|
||||
@ -490,7 +515,7 @@ test('借出时无配件但当前新增配件时进入版本确认,配件再
|
||||
await returnEquipmentBeforeDisposal(
|
||||
{
|
||||
params: { equipment_id: String(root.id) },
|
||||
body: { return_condition: '正常', confirmation_token: firstToken }
|
||||
body: { borrow_record_id: borrowRecord.id, return_condition: '正常', confirmation_token: firstToken }
|
||||
} as any,
|
||||
res as any
|
||||
)
|
||||
|
||||
@ -9,8 +9,9 @@ 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 { approveBatchDisposal, approveDisposal, createBatchDisposal, getDisposalList, previewBatchDisposal } = await import('../disposalController')
|
||||
const { borrowEquipment, returnEquipment } = await import('../borrowController')
|
||||
const { approveBatchDisposal, approveDisposal, cancelDisposal, completeDisposal, createBatchDisposal,
|
||||
getDisposalList, previewBatchDisposal } = await import('../disposalController')
|
||||
const { borrowEquipment, returnEquipment, returnEquipmentBeforeDisposal } = await import('../borrowController')
|
||||
const prefix = `disp-${randomUUID().slice(0, 12)}`
|
||||
const userIds: number[] = []
|
||||
const personIds: number[] = []
|
||||
@ -43,6 +44,7 @@ test('批量报废在本机隔离 MySQL 验证完整资产树、事务和审批
|
||||
}
|
||||
const submit = (assets: { equipment_id: number; item_ids: number[];
|
||||
auto_return_token?: string;
|
||||
auto_return_condition?: '正常' | '损坏';
|
||||
confirmed_quantities?: { equipment_id: number; total_quantity: number }[] }[], ip?: string) => call(createBatchDisposal,
|
||||
{ assets, disposal_reason: '设备老化', disposal_method: '报废', notes: '本机验证' }, ip)
|
||||
const assetLines = (content: string) => {
|
||||
@ -220,11 +222,14 @@ test('批量报废在本机隔离 MySQL 验证完整资产树、事务和审批
|
||||
assert.equal(available.blocked_reason, null)
|
||||
assert.deepEqual(offered.items.map((item: { id: number }) => item.id), [checkedOut.id, accessory.id])
|
||||
|
||||
const selection = (candidate: any) => ({
|
||||
const selection = (candidate: any, auto_return_condition?: '正常' | '损坏') => ({
|
||||
equipment_id: candidate.equipment_id, item_ids: candidate.items.map((item: { id: number }) => item.id),
|
||||
auto_return_token: candidate.auto_return_token
|
||||
auto_return_token: candidate.auto_return_token, auto_return_condition
|
||||
})
|
||||
const selected = [selection(offered), selection(available), selection(offeredAnother)]
|
||||
const selected = [selection(offered, '损坏'), selection(available), selection(offeredAnother, '正常')]
|
||||
const missingCondition = await submit([selection(offered)])
|
||||
assert.equal(missingCondition.status, 422)
|
||||
assert.match(missingCondition.body.message, /刷新页面.*实际状况/)
|
||||
const noConsent = await submit([{ equipment_id: checkedOut.id, item_ids: [checkedOut.id, accessory.id] }])
|
||||
assert.equal(noConsent.status, 409)
|
||||
assert.match(noConsent.body.message, /已借出/)
|
||||
@ -264,7 +269,7 @@ test('批量报废在本机隔离 MySQL 验证完整资产树、事务和审批
|
||||
assert.equal(await pendingNotices(), noticeCount + 1)
|
||||
const returned = await prisma.borrowRecord.findMany({ where: { id: borrowIds }, orderBy: { id: 'asc' } })
|
||||
assert.deepEqual(returned.map(row => [row.status, row.return_time !== null, row.return_condition]), [
|
||||
['已归还', true, '正常'], ['已归还', true, '正常'], ['已借出', false, '正常']
|
||||
['已归还', true, '损坏'], ['已归还', true, '正常'], ['已借出', false, '正常']
|
||||
])
|
||||
const movement = await prisma.assetTransferRecord.findMany({
|
||||
where: { root_equipment_id: returnedRoots, action_type: 'return', operated_by: applicant.id },
|
||||
@ -277,6 +282,22 @@ test('批量报废在本机隔离 MySQL 验证完整资产树、事务和审批
|
||||
assert.deepEqual(returnedTree.map(item => [item.status, item.department_id, item.remaining_quantity, item.storage_location_id, item.parent_id]), [
|
||||
['待报废', null, 1, location.id, null], ['待报废', null, 1, location.id, checkedOut.id]
|
||||
])
|
||||
const params = { id: String(ids[0]) }
|
||||
assert.equal((await call(approveDisposal, { approved: true }, '127.0.0.1', reviewer, params)).status, 200)
|
||||
const approved = await prisma.disposalRecord.findUniqueOrThrow({ where: { id: ids[0] } })
|
||||
await prisma.disposalItem.updateMany({ where: { disposal_id: ids[0] }, data: { snapshot_json: '{"status":"已损坏"}' } })
|
||||
const cancelled = await call(cancelDisposal, { cancel_reason: '需要继续核查' }, '127.0.0.1', reviewer, params)
|
||||
assert.equal(cancelled.status, 200, JSON.stringify(cancelled.body))
|
||||
const stored = await prisma.disposalRecord.findUniqueOrThrow({ where: { id: ids[0] }, include: { actions: true } })
|
||||
assert.deepEqual([stored.status, stored.approved_by, stored.approved_at, stored.completed_at],
|
||||
['cancelled', approved.approved_by, approved.approved_at, null])
|
||||
assert.equal(stored.actions.find(action => action.action_type === 'cancelled')?.detail, '需要继续核查')
|
||||
const restored = await prisma.equipment.findMany({ where: { id: { in: [checkedOut.id, accessory.id] } } })
|
||||
assert.ok(restored.every(item => item.status === '已损坏' && item.storage_location_id === location.id))
|
||||
assert.equal(await prisma.borrowRecord.count({ where: { id: borrowedId, status: '已归还', return_condition: '损坏' } }), 1)
|
||||
assert.equal(await prisma.dingTalkDelivery.count({ where: { event_type: 'disposal_cancelled', business_id: ids[0], recipient_user_id: reviewer.id } }), 1)
|
||||
assert.equal((await call(completeDisposal, {}, '127.0.0.1', applicant, params)).status, 409)
|
||||
assert.equal((await call(cancelDisposal, { cancel_reason: '重复撤销' }, '127.0.0.1', reviewer, params)).status, 409)
|
||||
})
|
||||
|
||||
await t.test('还后重借、配件变动、缺失或损坏的配件快照均不能使用旧确认归还', async () => {
|
||||
@ -287,11 +308,20 @@ test('批量报废在本机隔离 MySQL 验证完整资产树、事务和审批
|
||||
const manuallyReturned = await call(returnEquipment, { equipment_id: reborrowed.id, borrow_record_id: firstBorrow })
|
||||
assert.equal(manuallyReturned.status, 200)
|
||||
assert.equal(manuallyReturned.body.data.need_confirm, undefined)
|
||||
const alreadyReturned = await call(returnEquipmentBeforeDisposal, { borrow_record_id: firstBorrow, return_condition: '正常' },
|
||||
'127.0.0.1', applicant, { equipment_id: String(reborrowed.id) })
|
||||
assert.equal(alreadyReturned.status, 409)
|
||||
assert.match(alreadyReturned.body.message, /当前为可用.*刷新页面/)
|
||||
const nextBorrow = await borrow(reborrowed.id)
|
||||
const staleSingle = await call(returnEquipmentBeforeDisposal, { borrow_record_id: firstBorrow, return_condition: '正常' },
|
||||
'127.0.0.1', applicant, { equipment_id: String(reborrowed.id) })
|
||||
assert.equal(staleSingle.status, 409)
|
||||
assert.match(staleSingle.body.message, /借用单已变化/)
|
||||
const [newOffer] = await previewReturn(reborrowed.id)
|
||||
assert.ok(newOffer.auto_return_token)
|
||||
assert.notEqual(firstOffer.auto_return_token, newOffer.auto_return_token)
|
||||
const stale = await submit([{ equipment_id: reborrowed.id, item_ids: [reborrowed.id], auto_return_token: firstOffer.auto_return_token }])
|
||||
const stale = await submit([{ equipment_id: reborrowed.id, item_ids: [reborrowed.id],
|
||||
auto_return_token: firstOffer.auto_return_token, auto_return_condition: '正常' }])
|
||||
assert.equal(stale.status, 409)
|
||||
assert.match(stale.body.message, /重新预检/)
|
||||
const freshRecord = await prisma.borrowRecord.findUniqueOrThrow({ where: { id: nextBorrow } })
|
||||
@ -319,7 +349,7 @@ test('批量报废在本机隔离 MySQL 验证完整资产树、事务和审批
|
||||
const [afterMount] = await previewReturn(changingRoot.id)
|
||||
assert.equal(afterMount.auto_return_token, undefined)
|
||||
const changed = await submit([{ equipment_id: changingRoot.id, item_ids: [changingRoot.id, originalPart.id, attached.id],
|
||||
auto_return_token: beforeMount.auto_return_token }])
|
||||
auto_return_token: beforeMount.auto_return_token, auto_return_condition: '正常' }])
|
||||
assert.equal(changed.status, 409)
|
||||
assert.equal((await prisma.borrowRecord.findUniqueOrThrow({ where: { id: changingBorrowId } })).return_time, null)
|
||||
assert.equal(await prisma.disposalRecord.count({ where: { equipment_id: changingRoot.id } }), 0)
|
||||
@ -444,6 +474,28 @@ test('批量报废在本机隔离 MySQL 验证完整资产树、事务和审批
|
||||
assert.equal(await prisma.disposalAction.count({ where: { disposal_id: { in: [currentId, concurrentId] },
|
||||
action_type: { in: ['approved', 'rejected'] } } }), 2)
|
||||
})
|
||||
|
||||
await t.test('同一已审批报废单并发撤销与完成时仅一个动作成功', async () => {
|
||||
const root = await prisma.equipment.create({ data: data('cancel-race') })
|
||||
const part = await prisma.equipment.create({ data: { ...data('cancel-race-part', root.id), status: '已损坏' } })
|
||||
const id = await apply(root.id, [root.id, part.id])
|
||||
const params = { id: String(id) }
|
||||
assert.equal((await call(approveDisposal, { approved: true }, '127.0.0.1', reviewer, params)).status, 200)
|
||||
const [cancelled, completed] = await Promise.all([
|
||||
call(cancelDisposal, { cancel_reason: '继续使用' }, '127.0.0.1', reviewer, params),
|
||||
call(completeDisposal, {}, '127.0.0.1', applicant, params)
|
||||
])
|
||||
assert.deepEqual([cancelled.status, completed.status].sort(), [200, 409])
|
||||
const wasCancelled = cancelled.status === 200
|
||||
const record = await prisma.disposalRecord.findUniqueOrThrow({ where: { id }, include: { actions: true } })
|
||||
assert.equal(record.status, wasCancelled ? 'cancelled' : 'completed')
|
||||
assert.deepEqual(record.actions.filter(action => ['cancelled', 'completed'].includes(action.action_type))
|
||||
.map(action => action.action_type), [record.status])
|
||||
const equipment = await prisma.equipment.findMany({ where: { id: { in: [root.id, part.id] } }, orderBy: { id: 'asc' } })
|
||||
assert.deepEqual(equipment.map(item => item.status), wasCancelled ? ['可用', '已损坏'] : ['已报废', '已报废'])
|
||||
assert.equal(await prisma.dingTalkDelivery.count({ where: { business_id: id, recipient_user_id: reviewer.id,
|
||||
event_type: { in: ['disposal_cancelled', 'disposal_completed'] } } }), 1)
|
||||
})
|
||||
} finally {
|
||||
for (const [key, value] of Object.entries(previousEnv)) {
|
||||
if (value === undefined) delete process.env[key]
|
||||
|
||||
@ -128,7 +128,8 @@ test('已丢失主资产或配件不能申请报废,写入前拒绝且不改
|
||||
disposalRecord: { create: async () => { writes++; return { id: 1 } } }
|
||||
})
|
||||
const { res, state } = createResponse()
|
||||
await createDisposal({ body: { equipment_id: root.id, item_ids: [root.id, child.id], disposal_reason: '丢失后报废', disposal_method: '报废' } } as any, res as any)
|
||||
await createDisposal({ body: { equipment_id: root.id, item_ids: [root.id, child.id], disposal_reason: '丢失后报废',
|
||||
disposal_method: '报废', confirmed_quantities: [root, child].map(item => ({ equipment_id: item.id, total_quantity: item.total_quantity })) } } as any, res as any)
|
||||
assert.equal(state.statusCode, 422)
|
||||
assert.match(state.body.message, /已丢失.*不能申请报废/)
|
||||
assert.equal(writes, 0)
|
||||
@ -234,6 +235,7 @@ test('主资产仍挂载未勾选配件时申请报废返回 409 且不写状态
|
||||
body: {
|
||||
equipment_id: 10,
|
||||
item_ids: [10],
|
||||
confirmed_quantities: [{ equipment_id: 10, total_quantity: 1 }],
|
||||
disposal_reason: '设备老化',
|
||||
disposal_method: '报废',
|
||||
estimated_value: 0
|
||||
@ -298,6 +300,7 @@ test('初读资产树后并发挂载新配件时报废申请中止且不写数
|
||||
body: {
|
||||
equipment_id: rootEquipment.id,
|
||||
item_ids: [rootEquipment.id],
|
||||
confirmed_quantities: [{ equipment_id: rootEquipment.id, total_quantity: 1 }],
|
||||
disposal_reason: '设备老化',
|
||||
disposal_method: '报废',
|
||||
estimated_value: 0
|
||||
@ -490,7 +493,7 @@ test('驳回报废时按每个 item.pre_status 分别恢复', async () => {
|
||||
}
|
||||
})
|
||||
|
||||
test('行政已处理列表包含全部已审批、已驳回和已完成记录,不按处理人收窄', async () => {
|
||||
test('行政已处理列表包含已撤销,按状态筛选且不按处理人收窄', async () => {
|
||||
const originalFindMany = prisma.disposalRecord.findMany
|
||||
const originalCount = prisma.disposalRecord.count
|
||||
const originalGroupBy = prisma.disposalRecord.groupBy
|
||||
@ -507,7 +510,8 @@ test('行政已处理列表包含全部已审批、已驳回和已完成记录
|
||||
}
|
||||
;(prisma.disposalRecord.count as any) = async () => 1
|
||||
;(prisma.disposalRecord.groupBy as any) = async () => [
|
||||
{ status: 'completed', _count: { _all: 1 } }
|
||||
{ status: 'completed', _count: { _all: 1 } },
|
||||
{ status: 'cancelled', _count: { _all: 1 } }
|
||||
]
|
||||
|
||||
try {
|
||||
@ -519,11 +523,15 @@ test('行政已处理列表包含全部已审批、已驳回和已完成记录
|
||||
|
||||
assert.equal(state.statusCode, 200)
|
||||
assert.deepEqual(capturedWhere.AND[1], {
|
||||
status: { in: ['approved', 'rejected', 'completed'] }
|
||||
status: { in: ['approved', 'rejected', 'completed', 'cancelled'] }
|
||||
})
|
||||
assert.doesNotMatch(JSON.stringify(capturedWhere), /approved_by|completed_by/)
|
||||
assert.equal(state.body.data.list[0].notes, '旧版处置备注')
|
||||
assert.equal(state.body.data.list[0].historical_notes, '旧版处置备注')
|
||||
assert.equal(state.body.data.summary.cancelled, 1)
|
||||
await getDisposalList({ query: { scope: 'processed', status: 'cancelled' } } as any, res as any)
|
||||
assert.equal(state.statusCode, 200)
|
||||
assert.deepEqual(capturedWhere.AND[1], { status: 'cancelled' })
|
||||
} finally {
|
||||
;(prisma.disposalRecord.findMany as any) = originalFindMany
|
||||
;(prisma.disposalRecord.count as any) = originalCount
|
||||
|
||||
@ -151,19 +151,21 @@ test('A-B / B-A 交叉挂载会被祖先链校验拦截', async () => {
|
||||
}
|
||||
})
|
||||
|
||||
test('挂载带后代的配件树时同步父资产部门和借出状态', async () => {
|
||||
test('多层挂载一次升序锁定祖先和配件树,再同步父资产部门和借出状态', async () => {
|
||||
const originalTransaction = prisma.$transaction
|
||||
const borrowedParent = { ...parent, status: '已借出', remaining_quantity: 0 }
|
||||
const borrowedParent = { ...parent, id: 9, parent_id: parent.id, status: '已借出', remaining_quantity: 0 }
|
||||
const updates: any[] = []
|
||||
const locks: number[][] = []
|
||||
|
||||
;(prisma.$transaction as any) = async (callback: any) => callback({
|
||||
$queryRaw: async (query: any) => readCurrentTree(
|
||||
query,
|
||||
[borrowedParent, child, grandchild]
|
||||
),
|
||||
$queryRaw: async (query: any) => {
|
||||
if (query.sql.startsWith('SELECT id FROM equipment')) locks.push(query.values)
|
||||
return readCurrentTree(query, [borrowedParent, child, grandchild])
|
||||
},
|
||||
equipment: {
|
||||
findUnique: async (args: any) => {
|
||||
if (args.where.id === 1) {
|
||||
if (args.where.id === parent.id) return parent
|
||||
if (args.where.id === borrowedParent.id) {
|
||||
return args.include?.children
|
||||
? { ...borrowedParent, children: [{ unit_price: child.unit_price }] }
|
||||
: borrowedParent
|
||||
@ -187,13 +189,14 @@ test('挂载带后代的配件树时同步父资产部门和借出状态', async
|
||||
try {
|
||||
const { res, state } = createResponse()
|
||||
await mountChild(
|
||||
{ params: { parentId: '1' }, body: { child_id: 2 } } as any,
|
||||
{ params: { parentId: String(borrowedParent.id) }, body: { child_id: 2 } } as any,
|
||||
res as any
|
||||
)
|
||||
|
||||
assert.equal(state.statusCode, 200)
|
||||
assert.deepEqual(locks, [[1, 2, 3, 9]])
|
||||
assert.equal(updates.length, 2)
|
||||
assert.equal(updates[0].data.parent_id, 1)
|
||||
assert.equal(updates[0].data.parent_id, borrowedParent.id)
|
||||
assert.equal(updates[0].data.mount_status, 'mounted')
|
||||
assert.equal(updates[1].data.parent_id, undefined)
|
||||
for (const update of updates) {
|
||||
@ -263,6 +266,38 @@ test('卸载配件树时整树恢复可用并清空部门', async () => {
|
||||
}
|
||||
})
|
||||
|
||||
test('挂载等待锁期间祖先发生变化时不写配件或历史', async () => {
|
||||
const originalTransaction = prisma.$transaction
|
||||
const nestedParent = { ...parent, id: 9, parent_id: parent.id }
|
||||
const otherAncestor = { ...parent, id: 4 }
|
||||
let locked = false
|
||||
let writes = 0
|
||||
;(prisma.$transaction as any) = async (callback: any) => callback({
|
||||
$queryRaw: async (query: any) => {
|
||||
assert.deepEqual(query.values, [1, 2, 9])
|
||||
locked = true
|
||||
return []
|
||||
},
|
||||
equipment: {
|
||||
findUnique: async ({ where }: any) => where.id === nestedParent.id
|
||||
? { ...nestedParent, parent_id: locked ? otherAncestor.id : parent.id }
|
||||
: [parent, child, otherAncestor].find(item => item.id === where.id),
|
||||
findMany: async () => [],
|
||||
updateMany: async () => { writes++; return { count: 1 } }
|
||||
},
|
||||
mountHistory: { create: async () => { writes++ } }
|
||||
})
|
||||
try {
|
||||
const { res, state } = createResponse()
|
||||
await mountChild({ params: { parentId: String(nestedParent.id) }, body: { child_id: child.id } } as any, res as any)
|
||||
assert.equal(state.statusCode, 409)
|
||||
assert.match(state.body.message, /父资产关系已变化/)
|
||||
assert.equal(writes, 0)
|
||||
} finally {
|
||||
;(prisma.$transaction as any) = originalTransaction
|
||||
}
|
||||
})
|
||||
|
||||
test('卸载接口拒绝直接把配件设为维修中或待报废', async () => {
|
||||
const originalTransaction = prisma.$transaction
|
||||
let transactionCount = 0
|
||||
@ -298,6 +333,7 @@ test('maintenance parent rejects mounting and unmounting before any child or his
|
||||
findUnique: async ({ where }: any) => where.id === parent.id
|
||||
? { ...parent, status: '维护中' }
|
||||
: { ...child, parent_id: parent.id, status: '维护中' },
|
||||
findMany: async () => [],
|
||||
updateMany: async () => { writes++; return { count: 1 } },
|
||||
update: async () => { writes++; return {} }
|
||||
},
|
||||
|
||||
@ -17,11 +17,10 @@ import {
|
||||
import { logOperation } from './operationLogController'
|
||||
import { completeLockedBorrowReturn } from '../services/borrowReturnService'
|
||||
import {
|
||||
AssetTreeConflictError,
|
||||
assertReturnConditionSupported,
|
||||
borrowAssetTree,
|
||||
createAssetMovementRecord,
|
||||
finalizeBorrowAnomalyReturnState,
|
||||
finalizeNormalReturnState,
|
||||
loadAndLockAssetTree,
|
||||
loadAssetTree,
|
||||
registerBorrowAnomalyAssetTree,
|
||||
@ -309,6 +308,7 @@ type DisposalReturnBorrowRecord = {
|
||||
id: number
|
||||
equipment_id: number
|
||||
person_id: number
|
||||
return_time: Date | null
|
||||
children_snapshot: string | null
|
||||
updated_at: Date
|
||||
}
|
||||
@ -318,6 +318,7 @@ const buildDisposalReturnConfirmationToken = buildReturnConfirmationToken
|
||||
|
||||
const returnEquipmentBeforeDisposalInTransaction = async (input: {
|
||||
equipmentId: number
|
||||
borrowRecordId: number
|
||||
returnCondition: string
|
||||
confirmationToken?: string
|
||||
operatedBy: number
|
||||
@ -325,30 +326,33 @@ const returnEquipmentBeforeDisposalInTransaction = async (input: {
|
||||
const items = await loadAndLockAssetTree(tx, input.equipmentId)
|
||||
const root = items[0]
|
||||
if (root.parent_id !== null) {
|
||||
throw new Error('挂载中的子资产不能单独入库或申请报废,请先卸载')
|
||||
throw new AssetTreeConflictError('资产已被挂载,请刷新页面并先卸载')
|
||||
}
|
||||
if (root.status !== '已借出') {
|
||||
throw new Error(`资产当前为${root.status},无需执行报废前入库`)
|
||||
throw new AssetTreeConflictError(`资产当前为${root.status},请刷新页面后重新操作`)
|
||||
}
|
||||
if (root.total_quantity !== 1 || root.remaining_quantity !== 0) {
|
||||
throw new Error('快捷入库仅支持单件资产;该资产存在多数量库存,请先逐笔归还后再申请报废')
|
||||
throw new AssetTreeConflictError('快捷入库仅支持单件资产,请刷新页面并逐笔归还后再申请报废')
|
||||
}
|
||||
|
||||
const activeBorrowRecords = await tx.$queryRaw<DisposalReturnBorrowRecord[]>(Prisma.sql`
|
||||
SELECT id, equipment_id, person_id, children_snapshot, updated_at
|
||||
SELECT id, equipment_id, person_id, return_time, children_snapshot, updated_at
|
||||
FROM borrow_record
|
||||
WHERE equipment_id = ${root.id} AND status = ${'已借出'}
|
||||
ORDER BY id
|
||||
FOR UPDATE
|
||||
`)
|
||||
if (activeBorrowRecords.length === 0) {
|
||||
throw new Error('资产状态为已借出,但没有对应的未归还记录,请先处理借用异常')
|
||||
throw new AssetTreeConflictError('资产状态为已借出,但没有对应的未归还记录,请刷新页面后核对借用单')
|
||||
}
|
||||
if (activeBorrowRecords.length > 1) {
|
||||
throw new Error('该资产存在多条未归还记录,请先逐笔归还后再申请报废')
|
||||
throw new AssetTreeConflictError('该资产存在多条未归还记录,请刷新页面并逐笔归还后再申请报废')
|
||||
}
|
||||
|
||||
const borrowRecord = activeBorrowRecords[0]
|
||||
if (borrowRecord.id !== input.borrowRecordId || borrowRecord.return_time !== null) {
|
||||
throw new AssetTreeConflictError('当前借用单已变化,请刷新页面后重新确认归还')
|
||||
}
|
||||
const childrenDiff = getLockedDisposalChildrenDiff(items, borrowRecord)
|
||||
const confirmationToken = buildDisposalReturnConfirmationToken(items, borrowRecord)
|
||||
if (childrenDiff && input.confirmationToken !== confirmationToken) {
|
||||
@ -362,33 +366,10 @@ const returnEquipmentBeforeDisposalInTransaction = async (input: {
|
||||
const notes = childrenDiff
|
||||
? `报废前快捷入库;配件变更:移除${childrenDiff.removed.length}个,新增${childrenDiff.added.length}个`
|
||||
: '报废前快捷入库'
|
||||
await createAssetMovementRecord(tx, {
|
||||
items,
|
||||
actionType: 'return',
|
||||
toDepartmentId: null,
|
||||
operatedBy: input.operatedBy,
|
||||
reason: notes
|
||||
const { returnState, returnTime } = await completeLockedBorrowReturn(tx, {
|
||||
items, borrowRecord, returnCondition: input.returnCondition, operatedBy: input.operatedBy,
|
||||
notes, requireUnreturned: true
|
||||
})
|
||||
|
||||
const returnTime = new Date()
|
||||
const updatedBorrowRecord = await tx.borrowRecord.updateMany({
|
||||
where: {
|
||||
id: borrowRecord.id,
|
||||
equipment_id: root.id,
|
||||
status: '已借出'
|
||||
},
|
||||
data: {
|
||||
return_time: returnTime,
|
||||
status: '已归还',
|
||||
return_condition: input.returnCondition,
|
||||
notes
|
||||
}
|
||||
})
|
||||
if (updatedBorrowRecord.count !== 1) {
|
||||
throw new Error('该借用记录已归还,请刷新后重试')
|
||||
}
|
||||
|
||||
const returnState = await finalizeNormalReturnState(tx, root, input.returnCondition, items)
|
||||
return {
|
||||
need_confirm: false as const,
|
||||
equipment_id: root.id,
|
||||
@ -768,6 +749,7 @@ export const returnEquipment = async (req: Request, res: Response) => {
|
||||
export const returnEquipmentBeforeDisposal = async (req: Request, res: Response) => {
|
||||
try {
|
||||
const equipmentId = parseNumber(req.params.equipment_id)
|
||||
const borrowRecordId = req.body?.borrow_record_id
|
||||
const returnCondition = String(req.body?.return_condition || '正常').trim()
|
||||
const confirmationToken = typeof req.body?.confirmation_token === 'string'
|
||||
? req.body.confirmation_token.trim()
|
||||
@ -780,6 +762,9 @@ export const returnEquipmentBeforeDisposal = async (req: Request, res: Response)
|
||||
if (!userId) {
|
||||
return errorResponse(res, '用户未登录', 401)
|
||||
}
|
||||
if (typeof borrowRecordId !== 'number' || !Number.isSafeInteger(borrowRecordId) || borrowRecordId <= 0) {
|
||||
return errorResponse(res, '缺少有效借用单,请刷新页面后重新确认归还', 422)
|
||||
}
|
||||
if (!['正常', '损坏'].includes(returnCondition)) {
|
||||
return errorResponse(res, '报废前快捷入库仅支持已收回的正常或损坏资产', 422)
|
||||
}
|
||||
@ -789,6 +774,7 @@ export const returnEquipmentBeforeDisposal = async (req: Request, res: Response)
|
||||
|
||||
const result = await returnEquipmentBeforeDisposalInTransaction({
|
||||
equipmentId,
|
||||
borrowRecordId,
|
||||
returnCondition,
|
||||
confirmationToken,
|
||||
operatedBy: userId
|
||||
|
||||
@ -329,7 +329,7 @@ const getDisposalVisibility = (res: Response): Prisma.DisposalRecordWhereInput =
|
||||
throw Object.assign(new Error('无权查看报废流程'), { status: 403 })
|
||||
}
|
||||
|
||||
const DISPOSAL_STATUSES = ['pending', 'approved', 'rejected', 'completed'] as const
|
||||
const DISPOSAL_STATUSES = ['pending', 'approved', 'rejected', 'completed', 'cancelled'] as const
|
||||
|
||||
const parseListPositiveInteger = (
|
||||
value: unknown,
|
||||
@ -420,7 +420,8 @@ export const createDisposal = async (req: Request, res: Response) => {
|
||||
const {
|
||||
equipment_id,
|
||||
item_ids,
|
||||
estimated_value
|
||||
estimated_value,
|
||||
confirmed_quantities
|
||||
} = req.body as Record<string, any>
|
||||
const userId = Number(res.locals.user?.id)
|
||||
const rootId = Number(equipment_id)
|
||||
@ -429,6 +430,8 @@ export const createDisposal = async (req: Request, res: Response) => {
|
||||
return errorResponse(res, '请选择要报废的主资产', 422)
|
||||
}
|
||||
const input = readDisposalSubmission(req.body)
|
||||
if (confirmed_quantities == null) return errorResponse(res, '缺少报废数量确认,请刷新页面后逐件核对数量', 422)
|
||||
const quantities = readConfirmedDisposalQuantities(confirmed_quantities)
|
||||
const estimatedValue = Number(estimated_value ?? 0)
|
||||
if (!Number.isFinite(estimatedValue) || estimatedValue < 0) {
|
||||
return errorResponse(res, '残值估价必须是大于或等于0的有效数字', 422)
|
||||
@ -445,6 +448,7 @@ export const createDisposal = async (req: Request, res: Response) => {
|
||||
? [...new Set(item_ids.map(Number).filter((id) => Number.isInteger(id) && id > 0))]
|
||||
: [rootId]
|
||||
assertDisposalItemsConfirmed(tree, requestedIds)
|
||||
assertConfirmedDisposalQuantities(tree, quantities)
|
||||
const blocked = getDisposalBlockedReason(tree)
|
||||
if (blocked) throw new Error(blocked)
|
||||
const occupancy = await getDisposalOccupancy(tx, tree.map(item => item.id))
|
||||
@ -578,7 +582,11 @@ export const createBatchDisposal = async (req: Request, res: Response) => {
|
||||
}
|
||||
const input = readDisposalSubmission(req.body)
|
||||
const rootIds: number[] = []
|
||||
const confirmed = new Map<number, { itemIds: number[]; quantities?: Map<number, number>; autoReturnToken?: string }>()
|
||||
const confirmed = new Map<number, {
|
||||
itemIds: number[]
|
||||
quantities?: Map<number, number>
|
||||
autoReturn?: { token: string; condition: '正常' | '损坏' }
|
||||
}>()
|
||||
const lockedIds = new Set<number>()
|
||||
for (const asset of assets) {
|
||||
if (!isEquipmentId(asset?.equipment_id) || !Array.isArray(asset.item_ids) ||
|
||||
@ -590,6 +598,9 @@ export const createBatchDisposal = async (req: Request, res: Response) => {
|
||||
(typeof asset.auto_return_token !== 'string' || !/^[a-f0-9]{64}$/.test(asset.auto_return_token))) {
|
||||
return errorResponse(res, '自动归还确认凭据无效,请重新预检', 422)
|
||||
}
|
||||
if (asset.auto_return_token && asset.auto_return_condition !== '正常' && asset.auto_return_condition !== '损坏') {
|
||||
return errorResponse(res, '缺少有效的自动归还状况,请刷新页面后选择实际状况(正常或损坏)', 422)
|
||||
}
|
||||
for (const id of asset.item_ids as number[]) {
|
||||
if (lockedIds.has(id)) return errorResponse(res, '批量报废明细包含重复资产', 422)
|
||||
lockedIds.add(id)
|
||||
@ -597,7 +608,8 @@ export const createBatchDisposal = async (req: Request, res: Response) => {
|
||||
rootIds.push(asset.equipment_id)
|
||||
confirmed.set(asset.equipment_id, {
|
||||
itemIds: asset.item_ids,
|
||||
autoReturnToken: asset.auto_return_token,
|
||||
autoReturn: asset.auto_return_token
|
||||
? { token: asset.auto_return_token, condition: asset.auto_return_condition } : undefined,
|
||||
quantities: asset.confirmed_quantities === undefined
|
||||
? undefined : readConfirmedDisposalQuantities(asset.confirmed_quantities)
|
||||
})
|
||||
@ -620,7 +632,7 @@ export const createBatchDisposal = async (req: Request, res: Response) => {
|
||||
for (const id of rootIds) {
|
||||
const tree = trees.get(id)!
|
||||
const confirmation = confirmed.get(id)!
|
||||
if (!confirmation.autoReturnToken) {
|
||||
if (!confirmation.autoReturn) {
|
||||
const blocked = getDisposalBlockedReason(tree)
|
||||
if (blocked) throw new DisposalConflictError(`${tree[0].equipment_code}:${blocked}`)
|
||||
}
|
||||
@ -628,22 +640,23 @@ export const createBatchDisposal = async (req: Request, res: Response) => {
|
||||
if (confirmation.quantities) assertConfirmedDisposalQuantities(tree, confirmation.quantities)
|
||||
}
|
||||
let occupancy = await getDisposalOccupancy(tx, [...lockedIds])
|
||||
const returnRoots = rootIds.filter(id => confirmed.get(id)!.autoReturnToken)
|
||||
const returnRoots = rootIds.filter(id => confirmed.get(id)!.autoReturn)
|
||||
if (returnRoots.length) {
|
||||
const returnBorrows = await loadDisposalAutoReturnBorrows(tx,
|
||||
returnRoots.flatMap(id => confirmed.get(id)!.itemIds), true)
|
||||
const returns = returnRoots.map(id => {
|
||||
const items = trees.get(id)!
|
||||
const eligible = getDisposalAutoReturn(items, occupancy, returnBorrows)
|
||||
if (!eligible || eligible.token !== confirmed.get(id)!.autoReturnToken) {
|
||||
const { token, condition } = confirmed.get(id)!.autoReturn!
|
||||
if (!eligible || eligible.token !== token) {
|
||||
throw new DisposalConflictError(`${items[0].equipment_code}:借用或资产状态已变化,请重新预检后确认归还`)
|
||||
}
|
||||
return { items, borrowRecord: eligible.record }
|
||||
return { items, borrowRecord: eligible.record, condition }
|
||||
})
|
||||
for (const { items, borrowRecord } of returns) {
|
||||
for (const { items, borrowRecord, condition } of returns) {
|
||||
holders.set(items[0].id, borrowRecord.person_nickname.trim() || borrowRecord.person_name.trim() || '未登记领用人')
|
||||
await completeLockedBorrowReturn(tx, {
|
||||
items, borrowRecord, returnCondition: '正常', operatedBy: userId,
|
||||
items, borrowRecord, returnCondition: condition, operatedBy: userId,
|
||||
reason: '批量报废前归还入库', requireUnreturned: true
|
||||
})
|
||||
}
|
||||
@ -733,7 +746,7 @@ export const getDisposalList = async (req: Request, res: Response) => {
|
||||
} else if (resolvedScope === 'pending') {
|
||||
summaryConditions.push({ status: 'pending' })
|
||||
} else if (resolvedScope === 'processed') {
|
||||
summaryConditions.push({ status: { in: ['approved', 'rejected', 'completed'] } })
|
||||
summaryConditions.push({ status: { in: ['approved', 'rejected', 'completed', 'cancelled'] } })
|
||||
}
|
||||
}
|
||||
|
||||
@ -789,7 +802,8 @@ export const getDisposalList = async (req: Request, res: Response) => {
|
||||
pending: 0,
|
||||
approved: 0,
|
||||
rejected: 0,
|
||||
completed: 0
|
||||
completed: 0,
|
||||
cancelled: 0
|
||||
}
|
||||
for (const group of statusGroups) {
|
||||
const count = group._count._all
|
||||
@ -944,6 +958,12 @@ const readDisposalDecision = (body: { approved?: unknown; reject_reason?: unknow
|
||||
|
||||
type DisposalDecision = ReturnType<typeof readDisposalDecision>
|
||||
|
||||
const restoreDisposalPreStatuses = async (tx: Prisma.TransactionClient, disposal: DisposalDecisionRecord) => {
|
||||
for (const item of disposal.items) {
|
||||
await updateEquipmentLifecycle(tx, item.equipment, item.pre_status, '待报废', item.parent_equipment_id)
|
||||
}
|
||||
}
|
||||
|
||||
const writeDisposalDecision = async (
|
||||
tx: Prisma.TransactionClient,
|
||||
disposal: DisposalDecisionRecord,
|
||||
@ -965,11 +985,7 @@ const writeDisposalDecision = async (
|
||||
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)
|
||||
}
|
||||
}
|
||||
if (!approved) await restoreDisposalPreStatuses(tx, disposal)
|
||||
await tx.disposalAction.create({
|
||||
data: {
|
||||
disposal_id: disposal.id, action_type: nextStatus, operator_id: userId,
|
||||
@ -1213,6 +1229,58 @@ export const approveBatchDisposal = async (req: Request, res: Response) => {
|
||||
}
|
||||
}
|
||||
|
||||
export const cancelDisposal = async (req: Request, res: Response) => {
|
||||
try {
|
||||
const { id: userId } = getCurrentUser(res)
|
||||
if (!isEquipmentId(userId)) return errorResponse(res, '用户未登录', 401)
|
||||
const disposalId = parseListPositiveInteger(req.params.id, '报废记录ID', 0)
|
||||
const reason = typeof req.body?.cancel_reason === 'string' ? req.body.cancel_reason.trim() : ''
|
||||
if (!reason) return errorResponse(res, '撤销原因不能为空', 422)
|
||||
const operator = res.locals.user?.name || res.locals.user?.username
|
||||
|
||||
await prisma.$transaction(async tx => {
|
||||
const disposal = await loadLockedDisposalDecision(tx, disposalId, 'approved')
|
||||
const updated = await tx.disposalRecord.updateMany({
|
||||
where: { id: disposalId, status: 'approved', completed_at: null },
|
||||
data: { status: 'cancelled' }
|
||||
})
|
||||
if (updated.count !== 1) throw new DisposalConflictError('该申请已处置或状态已变化,请刷新后查看')
|
||||
await restoreDisposalPreStatuses(tx, disposal)
|
||||
await tx.disposalAction.create({
|
||||
data: {
|
||||
disposal_id: disposalId, operator_id: userId, action_type: 'cancelled',
|
||||
from_status: 'approved', to_status: 'cancelled', detail: reason
|
||||
}
|
||||
})
|
||||
await tx.operationLog.create({
|
||||
data: {
|
||||
user_id: userId, username: res.locals.user?.username || operator || 'unknown',
|
||||
operation_type: '报废撤销', operation_details: `撤销资产 ${disposal.equipment_code} 的报废申请,原因:${reason}`,
|
||||
equipment_id: disposal.equipment_id, equipment_code: disposal.equipment_code, ip_address: req.ip || null
|
||||
}
|
||||
})
|
||||
const recipients = await getResultRecipients(tx, disposal.applied_by)
|
||||
const root = disposal.items.find(item => item.equipment_id === disposal.equipment_id)?.equipment
|
||||
await createBusinessNotification(tx, {
|
||||
...recipients, eventType: 'disposal_cancelled', businessType: 'disposal', businessId: disposalId,
|
||||
title: `报废已撤销:${disposal.equipment_code}`, content: `撤销原因:${reason}`,
|
||||
level: 'warning', actionUrl: `/workflows/disposals/${disposalId}`,
|
||||
dingTalk: {
|
||||
title: '资产报废已撤销', actionTitle: '查看结果',
|
||||
content: [
|
||||
`**资产:** ${assetNotificationName(root?.equipment_name, disposal.equipment_code)}`,
|
||||
`**撤销人:** ${escapeNotificationMarkdownInline(operator)}`,
|
||||
`**撤销原因:** ${escapeNotificationMarkdownInline(reason)}`
|
||||
].join('\n\n')
|
||||
}
|
||||
})
|
||||
}, { isolationLevel: Prisma.TransactionIsolationLevel.ReadCommitted })
|
||||
successResponse(res, null, '报废已撤销')
|
||||
} 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)
|
||||
|
||||
@ -9,7 +9,8 @@ import {
|
||||
refreshParentTotalValueWithChildren
|
||||
} from '../utils/assetValue'
|
||||
import {
|
||||
loadAndLockAssetTree,
|
||||
getAssetTreeFingerprint,
|
||||
loadAssetTree,
|
||||
lockEquipmentRows,
|
||||
type AssetTreeItem
|
||||
} from '../services/assetMovementService'
|
||||
@ -139,12 +140,12 @@ const updateAssetTreeState = async (
|
||||
}
|
||||
}
|
||||
|
||||
const ensureNoMountCycle = async (
|
||||
const loadMountAncestors = async (
|
||||
client: TransactionClient,
|
||||
parentId: number,
|
||||
childId: number
|
||||
attachingChildId?: number
|
||||
) => {
|
||||
if (parentId === childId) {
|
||||
if (parentId === attachingChildId) {
|
||||
throw new MountOperationError('父资产和子资产不能是同一条记录')
|
||||
}
|
||||
|
||||
@ -154,7 +155,7 @@ const ensureNoMountCycle = async (
|
||||
if (depth >= 100) {
|
||||
throw new MountOperationError('资产父子关系层级过深,请先检查资产关系', 409)
|
||||
}
|
||||
if (currentId === childId) {
|
||||
if (currentId === attachingChildId) {
|
||||
throw new MountOperationError('不能把资产挂载到自己的下级节点上')
|
||||
}
|
||||
if (visited.has(currentId)) {
|
||||
@ -162,13 +163,55 @@ const ensureNoMountCycle = async (
|
||||
}
|
||||
visited.add(currentId)
|
||||
|
||||
await lockEquipmentRows(client, [currentId])
|
||||
const current: { parent_id: number | null } | null = await client.equipment.findUnique({
|
||||
where: { id: currentId },
|
||||
select: { parent_id: true }
|
||||
})
|
||||
currentId = current?.parent_id ?? null
|
||||
if (!current) {
|
||||
throw new MountOperationError(currentId === parentId ? '父资产不存在' : '父资产关系已变化,请刷新后重试',
|
||||
currentId === parentId ? 404 : 409)
|
||||
}
|
||||
currentId = current.parent_id
|
||||
}
|
||||
return [...visited]
|
||||
}
|
||||
|
||||
const lockMountAssets = async (
|
||||
client: TransactionClient,
|
||||
parentId: number,
|
||||
children: { id: number; missingMessage: string; missingStatus?: number }[],
|
||||
attachingChildId?: number
|
||||
) => {
|
||||
const ancestors = await loadMountAncestors(client, parentId, attachingChildId)
|
||||
const trees = await Promise.all(children.map(async child => {
|
||||
try {
|
||||
return await loadAssetTree(client, child.id)
|
||||
} catch (error) {
|
||||
if (error instanceof Error && error.message === '资产不存在') {
|
||||
throw new MountOperationError(child.missingMessage, child.missingStatus ?? 404)
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}))
|
||||
await lockEquipmentRows(client, [...ancestors, ...trees.flatMap(tree => tree.map(item => item.id))])
|
||||
const currentAncestors = await loadMountAncestors(client, parentId)
|
||||
if (ancestors.join(',') !== currentAncestors.join(',')) {
|
||||
throw new MountOperationError('父资产关系已变化,请刷新后重试', 409)
|
||||
}
|
||||
const currentTrees = await Promise.all(children.map(async child => {
|
||||
try {
|
||||
return await loadAssetTree(client, child.id)
|
||||
} catch (error) {
|
||||
if (error instanceof Error && error.message === '资产不存在') {
|
||||
throw new MountOperationError('配件已变化,请刷新后重试', 409)
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}))
|
||||
if (trees.some((tree, index) => getAssetTreeFingerprint(tree) !== getAssetTreeFingerprint(currentTrees[index]))) {
|
||||
throw new MountOperationError('配件状态或挂载关系已变化,请刷新后重试', 409)
|
||||
}
|
||||
return currentTrees
|
||||
}
|
||||
|
||||
const getMountErrorStatus = (error: any) => {
|
||||
@ -196,7 +239,8 @@ export const mountChild = async (req: Request, res: Response) => {
|
||||
}
|
||||
|
||||
const updatedParent = await prisma.$transaction(async (tx) => {
|
||||
await lockEquipmentRows(tx, [numericParentId, numericChildId])
|
||||
const [childTree] = await lockMountAssets(tx, numericParentId,
|
||||
[{ id: numericChildId, missingMessage: '子资产不存在' }], numericChildId)
|
||||
const [parent, child] = await Promise.all([
|
||||
tx.equipment.findUnique({
|
||||
where: { id: numericParentId },
|
||||
@ -219,8 +263,6 @@ export const mountChild = async (req: Request, res: Response) => {
|
||||
if (child.parent_id !== null || !['none', 'unmounted'].includes(child.mount_status)) {
|
||||
throw new MountOperationError('该配件已被挂载或关系已变化,请刷新后重试', 409)
|
||||
}
|
||||
await ensureNoMountCycle(tx, numericParentId, numericChildId)
|
||||
const childTree = await loadAndLockAssetTree(tx, numericChildId)
|
||||
await ensureAssetTreeAttachable(tx, childTree, '子资产树')
|
||||
await updateAssetTreeState(tx, childTree, {
|
||||
rootParentId: numericParentId,
|
||||
@ -284,7 +326,7 @@ export const unmountChild = async (req: Request, res: Response) => {
|
||||
}
|
||||
|
||||
await prisma.$transaction(async (tx) => {
|
||||
await lockEquipmentRows(tx, [numericParentId, numericChildId])
|
||||
const [childTree] = await lockMountAssets(tx, numericParentId, [{ id: numericChildId, missingMessage: '子资产不存在' }])
|
||||
const [parent, child] = await Promise.all([
|
||||
tx.equipment.findUnique({ where: { id: numericParentId } }),
|
||||
tx.equipment.findUnique({ where: { id: numericChildId } })
|
||||
@ -295,7 +337,6 @@ export const unmountChild = async (req: Request, res: Response) => {
|
||||
throw new MountOperationError('该配件未挂载到此资产或关系已变化', 409)
|
||||
}
|
||||
ensureParentMountOperable(parent, '父资产')
|
||||
const childTree = await loadAndLockAssetTree(tx, numericChildId)
|
||||
await updateAssetTreeState(tx, childTree, {
|
||||
rootParentId: null,
|
||||
rootMountStatus: 'unmounted',
|
||||
@ -350,7 +391,10 @@ export const replaceChild = async (req: Request, res: Response) => {
|
||||
}
|
||||
|
||||
await prisma.$transaction(async (tx) => {
|
||||
await lockEquipmentRows(tx, [numericParentId, numericOldChildId, numericNewChildId])
|
||||
const [oldChildTree, newChildTree] = await lockMountAssets(tx, numericParentId, [
|
||||
{ id: numericOldChildId, missingMessage: '旧配件未挂载到此资产或关系已变化', missingStatus: 409 },
|
||||
{ id: numericNewChildId, missingMessage: '新配件不存在' }
|
||||
], numericNewChildId)
|
||||
const [parent, oldChild, newChild] = await Promise.all([
|
||||
tx.equipment.findUnique({
|
||||
where: { id: numericParentId },
|
||||
@ -377,9 +421,6 @@ export const replaceChild = async (req: Request, res: Response) => {
|
||||
throw new MountOperationError('新配件已被挂载或关系已变化,请刷新后重试', 409)
|
||||
}
|
||||
ensureParentMountOperable(parent, '父资产')
|
||||
await ensureNoMountCycle(tx, numericParentId, numericNewChildId)
|
||||
const oldChildTree = await loadAndLockAssetTree(tx, numericOldChildId)
|
||||
const newChildTree = await loadAndLockAssetTree(tx, numericNewChildId)
|
||||
await ensureAssetTreeAttachable(tx, newChildTree, '新配件树')
|
||||
await updateAssetTreeState(tx, oldChildTree, {
|
||||
rootParentId: null,
|
||||
|
||||
@ -8,6 +8,7 @@ import {
|
||||
approveDisposal,
|
||||
approveBatchDisposal,
|
||||
completeDisposal,
|
||||
cancelDisposal,
|
||||
getEquipmentDisposalHistory
|
||||
} from '../controllers/disposalController'
|
||||
import { returnEquipmentBeforeDisposal } from '../controllers/borrowController'
|
||||
@ -30,6 +31,7 @@ router.get('/equipment/:equipment_id/history', requirePermission(PERMISSIONS.ASS
|
||||
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/cancel', requirePermission(PERMISSIONS.DISPOSALS_APPROVE), cancelDisposal)
|
||||
router.put('/:id/complete', requirePermission(PERMISSIONS.DISPOSALS_COMPLETE), completeDisposal)
|
||||
|
||||
export default router
|
||||
|
||||
@ -62,7 +62,7 @@ export const lockEquipmentRows = async (
|
||||
)
|
||||
}
|
||||
|
||||
const getAssetTreeFingerprint = (items: AssetTreeItem[]) => JSON.stringify(
|
||||
export const getAssetTreeFingerprint = (items: AssetTreeItem[]) => JSON.stringify(
|
||||
items
|
||||
.map((item) => ({
|
||||
id: item.id,
|
||||
|
||||
24
frontend/scripts/test-disposal-import.ts
Normal file
24
frontend/scripts/test-disposal-import.ts
Normal file
@ -0,0 +1,24 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { test } from 'node:test'
|
||||
import * as XLSX from 'xlsx'
|
||||
import { parseDisposalImport } from '../src/utils/disposalImport.ts'
|
||||
|
||||
test('报废清单跳过隐藏行和隐藏工作表,保留可见编码及重复项', () => {
|
||||
const workbook = XLSX.utils.book_new()
|
||||
const visible = XLSX.utils.aoa_to_sheet([
|
||||
['资产编码', '', '设备编号'],
|
||||
['JS-PC-0001', '', 'JS-PC-0002'],
|
||||
['JS-PC-0098', '', 'JS-PC-0099'],
|
||||
['JS-PC-0001', '', 'JS-PC-0003']
|
||||
])
|
||||
visible['!rows'] = [{}, {}, { hidden: true }, {}]
|
||||
XLSX.utils.book_append_sheet(workbook, visible, '当前清单')
|
||||
XLSX.utils.book_append_sheet(workbook, XLSX.utils.aoa_to_sheet([['资产编码'], ['JS-PC-0096']]), '历史')
|
||||
XLSX.utils.book_append_sheet(workbook, XLSX.utils.aoa_to_sheet([['资产编码'], ['JS-PC-0097']]), '归档')
|
||||
XLSX.utils.book_set_sheet_visibility(workbook, '历史', 1)
|
||||
XLSX.utils.book_set_sheet_visibility(workbook, '归档', 2)
|
||||
|
||||
const source = XLSX.write(workbook, { type: 'array', bookType: 'xlsx' })
|
||||
|
||||
assert.deepEqual(parseDisposalImport(source), ['JS-PC-0001', 'JS-PC-0002', 'JS-PC-0001', 'JS-PC-0003'])
|
||||
})
|
||||
@ -9,7 +9,7 @@ export interface DisposalRecord {
|
||||
disposal_method: string
|
||||
estimated_value: number
|
||||
actual_value?: number
|
||||
status: 'pending' | 'approved' | 'rejected' | 'completed'
|
||||
status: 'pending' | 'approved' | 'rejected' | 'completed' | 'cancelled'
|
||||
applied_by: number
|
||||
applied_at: string
|
||||
approved_by?: number
|
||||
@ -73,6 +73,7 @@ export interface DisposalAction {
|
||||
export interface CreateDisposalParams {
|
||||
equipment_id: number
|
||||
item_ids?: number[]
|
||||
confirmed_quantities: ConfirmedDisposalQuantity[]
|
||||
disposal_reason: string
|
||||
disposal_method: string
|
||||
estimated_value: number
|
||||
@ -103,6 +104,7 @@ export interface DisposalSummary {
|
||||
approved: number
|
||||
rejected: number
|
||||
completed: number
|
||||
cancelled: number
|
||||
}
|
||||
|
||||
export interface DisposalListData {
|
||||
@ -141,6 +143,7 @@ export interface CreateBatchDisposalParams {
|
||||
item_ids: number[]
|
||||
confirmed_quantities?: ConfirmedDisposalQuantity[]
|
||||
auto_return_token?: string
|
||||
auto_return_condition?: DisposalReturnCondition
|
||||
}>
|
||||
disposal_reason: string
|
||||
disposal_method: string
|
||||
@ -155,8 +158,11 @@ export const createBatchDisposal = (data: CreateBatchDisposalParams) => request
|
||||
.post<ApiResponse<{ count: number; disposal_ids: number[] }>>('/disposal/batch', data, { timeout: 60000 })
|
||||
.then((response) => response.data)
|
||||
|
||||
export type DisposalReturnCondition = '正常' | '损坏'
|
||||
|
||||
export const returnEquipmentBeforeDisposal = (equipmentId: number, data: {
|
||||
return_condition: '正常' | '损坏'
|
||||
borrow_record_id: number
|
||||
return_condition: DisposalReturnCondition
|
||||
confirmation_token?: string
|
||||
}) => request
|
||||
.post<ApiResponse<DisposalReturnPreparationResult>>(
|
||||
@ -204,5 +210,8 @@ export const approveBatchDisposal = (data: {
|
||||
export const completeDisposal = (id: number, data: { actual_value?: number; completion_notes?: string }) =>
|
||||
request.put(`/disposal/${id}/complete`, data)
|
||||
|
||||
export const cancelDisposal = (id: number, data: { cancel_reason: string }) =>
|
||||
request.put(`/disposal/${id}/cancel`, data)
|
||||
|
||||
export const getEquipmentDisposalHistory = (equipmentId: number) =>
|
||||
request.get(`/disposal/equipment/${equipmentId}/history`)
|
||||
|
||||
@ -93,6 +93,15 @@
|
||||
>
|
||||
自动归还
|
||||
</label>
|
||||
<button
|
||||
v-if="selectedAutoReturns.length && previewScope === 'eligible'"
|
||||
type="button"
|
||||
class="btn-secondary disposal-quiet-button"
|
||||
:disabled="busy"
|
||||
@click="markAllReturnsNormal"
|
||||
>
|
||||
全部正常
|
||||
</button>
|
||||
<label
|
||||
v-if="previewScope === 'eligible' && eligibleCandidates.length"
|
||||
class="disposal-toolbar-choice"
|
||||
@ -138,17 +147,32 @@
|
||||
<span class="text-right text-xs tabular-nums text-text-secondary">
|
||||
{{ candidate.items[0]?.total_quantity === undefined ? '—' : candidate.items[0].total_quantity + ' 件' }}
|
||||
</span>
|
||||
<button
|
||||
v-if="candidate.items.length > 1"
|
||||
type="button"
|
||||
class="btn-secondary disposal-quiet-button disposal-accessory-toggle"
|
||||
:aria-expanded="expandedCodes.has(candidate.equipment_code)"
|
||||
:aria-label="'查看 ' + (candidate.items.length - 1) + ' 项配件,' + candidate.equipment_code"
|
||||
@click="toggleAccessories(candidate.equipment_code)"
|
||||
>
|
||||
含 {{ candidate.items.length - 1 }} 项配件
|
||||
<ChevronDownIcon class="h-3.5 w-3.5 shrink-0" aria-hidden="true" />
|
||||
</button>
|
||||
<div class="flex flex-col items-stretch">
|
||||
<select
|
||||
v-if="candidate.auto_return_token && selectedIds.includes(candidate.equipment_id)"
|
||||
v-model="returnConditions[candidate.equipment_id]"
|
||||
class="select disposal-return-condition"
|
||||
:aria-label="candidate.equipment_code + ' 归还状况'"
|
||||
:disabled="busy"
|
||||
>
|
||||
<option :value="undefined" disabled>归还状况</option>
|
||||
<option value="正常">正常</option>
|
||||
<option value="损坏" :disabled="hasMultiQuantityItems(candidate)">
|
||||
{{ hasMultiQuantityItems(candidate) ? '损坏需逐件处理' : candidate.items.length > 1 ? '整组损坏' : '损坏' }}
|
||||
</option>
|
||||
</select>
|
||||
<button
|
||||
v-if="candidate.items.length > 1"
|
||||
type="button"
|
||||
class="btn-secondary disposal-quiet-button disposal-accessory-toggle"
|
||||
:aria-expanded="expandedCodes.has(candidate.equipment_code)"
|
||||
:aria-label="'查看 ' + (candidate.items.length - 1) + ' 项配件,' + candidate.equipment_code"
|
||||
@click="toggleAccessories(candidate.equipment_code)"
|
||||
>
|
||||
含 {{ candidate.items.length - 1 }} 项配件
|
||||
<ChevronDownIcon class="h-3.5 w-3.5 shrink-0" aria-hidden="true" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<ul v-if="expandedCodes.has(candidate.equipment_code)" class="disposal-accessory-list" aria-label="配件明细">
|
||||
<li
|
||||
@ -222,6 +246,9 @@
|
||||
<p v-if="eligibleCandidates.length" class="text-sm tabular-nums text-text-secondary" aria-live="polite">
|
||||
<span class="font-medium text-text-primary">已选 {{ selectedCandidates.length }} 项</span>
|
||||
<span v-if="selectedQuantity !== null && selectedQuantity !== selectedCandidates.length"> · {{ selectedQuantity }} 件</span>
|
||||
<span v-if="selectedAutoReturns.length" class="block text-xs text-status-warning">
|
||||
提交时立即归还 {{ selectedAutoReturns.length }} 项<template v-if="missingReturnConditions"> · {{ missingReturnConditions }} 项待选状况</template>
|
||||
</span>
|
||||
</p>
|
||||
<div class="disposal-dialog-actions">
|
||||
<button type="button" class="btn-secondary" :disabled="submitting" @click="close">取消</button>
|
||||
@ -250,7 +277,8 @@ import {
|
||||
previewBatchDisposal,
|
||||
type BatchDisposalCandidate,
|
||||
type BatchDisposalPreview,
|
||||
type BatchDisposalPreviewParams
|
||||
type BatchDisposalPreviewParams,
|
||||
type DisposalReturnCondition
|
||||
} from '@/api/disposal'
|
||||
|
||||
const props = defineProps<{ equipmentIds: number[]; pickAssets?: boolean }>()
|
||||
@ -274,6 +302,7 @@ const loading = ref(false)
|
||||
const submitting = ref(false)
|
||||
const autoReturnEnabled = ref(false)
|
||||
const selectedIds = ref<number[]>([])
|
||||
const returnConditions = ref<Partial<Record<number, DisposalReturnCondition>>>({})
|
||||
const expandedCodes = ref(new Set<string>())
|
||||
const previewScope = ref<'eligible' | 'blocked'>('eligible')
|
||||
const previewPage = ref(1)
|
||||
@ -286,6 +315,9 @@ const canApply = (candidate: BatchDisposalCandidate): candidate is BatchDisposal
|
||||
candidate.equipment_id !== null && candidate.items.length > 0 &&
|
||||
(candidate.auto_return_token ? autoReturnEnabled.value : !candidate.blocked_reason)
|
||||
|
||||
const hasMultiQuantityItems = (candidate: BatchDisposalCandidate) =>
|
||||
candidate.items.some((item) => (item.total_quantity ?? 0) > 1)
|
||||
|
||||
const candidateSelectionLabel = (candidate: BatchDisposalCandidate) => {
|
||||
const prefix = candidate.auto_return_token ? '归还后' : ''
|
||||
return candidate.items.length > 1
|
||||
@ -319,13 +351,23 @@ const selectedCandidates = computed(() => {
|
||||
})
|
||||
const allEligibleSelected = computed(() => eligibleCandidates.value.length > 0 &&
|
||||
selectedCandidates.value.length === eligibleCandidates.value.length)
|
||||
const selectedAutoReturns = computed(() => selectedCandidates.value.filter((candidate) => candidate.auto_return_token))
|
||||
const missingReturnConditions = computed(() =>
|
||||
selectedAutoReturns.value.filter((candidate) => !returnConditions.value[candidate.equipment_id]).length
|
||||
)
|
||||
const selectedQuantity = computed(() => {
|
||||
const quantities = selectedCandidates.value.flatMap((candidate) => candidate.items.map((item) => item.total_quantity))
|
||||
return quantities.every((quantity) => quantity !== undefined)
|
||||
? quantities.reduce((sum, quantity) => sum + quantity, 0)
|
||||
: null
|
||||
})
|
||||
const canSubmit = computed(() => !picking.value && !busy.value && selectedCandidates.value.length > 0 && Boolean(reason.value.trim()))
|
||||
const canSubmit = computed(() => !picking.value && !busy.value && selectedCandidates.value.length > 0 &&
|
||||
!missingReturnConditions.value && Boolean(reason.value.trim()))
|
||||
|
||||
const markAllReturnsNormal = () => {
|
||||
if (busy.value) return
|
||||
for (const candidate of selectedAutoReturns.value) returnConditions.value[candidate.equipment_id] = '正常'
|
||||
}
|
||||
|
||||
const changePreviewScope = (scope: 'eligible' | 'blocked') => {
|
||||
if (scope === previewScope.value) return
|
||||
@ -339,6 +381,7 @@ const changeAutoReturn = (event: Event) => {
|
||||
if (!autoReturnEnabled.value) {
|
||||
const autoReturnIds = new Set(autoReturnCandidates.value.map((candidate) => candidate.equipment_id))
|
||||
selectedIds.value = selectedIds.value.filter((id) => !autoReturnIds.has(id))
|
||||
returnConditions.value = {}
|
||||
}
|
||||
previewScope.value = eligibleCandidates.value.length ? 'eligible' : 'blocked'
|
||||
previewPage.value = 1
|
||||
@ -368,6 +411,7 @@ const resetPreview = () => {
|
||||
preview.value = null
|
||||
autoReturnEnabled.value = false
|
||||
selectedIds.value = []
|
||||
returnConditions.value = {}
|
||||
expandedCodes.value.clear()
|
||||
previewPage.value = 1
|
||||
previewScope.value = 'eligible'
|
||||
@ -455,7 +499,10 @@ const submit = async () => {
|
||||
equipment_id: candidate.equipment_id,
|
||||
item_ids: candidate.items.map((item) => item.id),
|
||||
confirmed_quantities: quantities.length === candidate.items.length ? quantities : undefined,
|
||||
...(autoReturnEnabled.value && candidate.auto_return_token ? { auto_return_token: candidate.auto_return_token } : {})
|
||||
...(candidate.auto_return_token ? {
|
||||
auto_return_token: candidate.auto_return_token,
|
||||
auto_return_condition: returnConditions.value[candidate.equipment_id]
|
||||
} : {})
|
||||
}
|
||||
})
|
||||
submitting.value = true
|
||||
@ -637,6 +684,13 @@ onMounted(() => {
|
||||
background: var(--bg-tertiary);
|
||||
}
|
||||
|
||||
.disposal-return-condition {
|
||||
min-height: 36px;
|
||||
margin-block: var(--space-1);
|
||||
padding-block: var(--space-1);
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
.disposal-asset-choice {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
|
||||
@ -120,6 +120,7 @@ export interface EquipmentTreeNode {
|
||||
equipment_model?: string
|
||||
equipment_type?: string
|
||||
unit_price?: number
|
||||
total_quantity?: number
|
||||
status?: string
|
||||
mount_status?: string
|
||||
parent_id?: number | null
|
||||
|
||||
@ -3,12 +3,12 @@ import * as XLSX from 'xlsx'
|
||||
const codeHeaders = new Set(['编码', '资产编码', '设备编码', '资产编号', '设备编号', '资产代码', '设备代码'])
|
||||
|
||||
export const parseDisposalImport = (source: ArrayBuffer | string): string[] => {
|
||||
const workbook = XLSX.read(source, { type: typeof source === 'string' ? 'string' : 'array', raw: true })
|
||||
const workbook = XLSX.read(source, { type: typeof source === 'string' ? 'string' : 'array', raw: true, cellStyles: true })
|
||||
const codes: string[] = []
|
||||
|
||||
for (const [index, name] of workbook.SheetNames.entries()) {
|
||||
if (workbook.Workbook?.Sheets?.[index]?.Hidden) continue
|
||||
const rows = XLSX.utils.sheet_to_json<string[]>(workbook.Sheets[name], { header: 1, raw: false, defval: '' })
|
||||
const rows = XLSX.utils.sheet_to_json<string[]>(workbook.Sheets[name], { header: 1, raw: false, defval: '', skipHidden: true })
|
||||
for (const [rowIndex, row] of rows.entries()) {
|
||||
const columns = row.flatMap((cell, index) => codeHeaders.has(cell.replace(/\s/g, '')) ? [index] : [])
|
||||
if (!columns.length) continue
|
||||
|
||||
@ -368,7 +368,7 @@
|
||||
|
||||
<!-- 报废前置处理提示 -->
|
||||
<div
|
||||
v-if="showDisposalPrerequisite && canApplyDisposal"
|
||||
v-if="disposalPrerequisite && disposalPrerequisite.id === Number(route.params.id) && canApplyDisposal"
|
||||
class="sheet-backdrop"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
@ -377,34 +377,29 @@
|
||||
<div class="sheet-panel max-w-lg">
|
||||
<div class="flex flex-wrap items-start justify-between gap-3">
|
||||
<div>
|
||||
<h3 id="disposal-prerequisite-title" class="text-xl font-semibold text-text-primary">{{ disposalPrerequisiteTitle }}</h3>
|
||||
<p class="mt-2 text-sm text-text-secondary">{{ disposalBlockReason }}</p>
|
||||
<h3 id="disposal-prerequisite-title" class="text-xl font-semibold text-text-primary">{{ disposalPreparationNotice ? '入库完成' : disposalPrerequisite.title }}</h3>
|
||||
<p class="mt-2 text-sm text-text-secondary">{{ disposalPreparationNotice || disposalPrerequisite.reason }}</p>
|
||||
</div>
|
||||
<span class="badge badge-warning">当前状态:{{ currentEquipment?.status }}</span>
|
||||
<span v-if="!disposalPreparationNotice" class="badge badge-warning">{{ disposalPrerequisite.status }}</span>
|
||||
</div>
|
||||
|
||||
<dl v-if="currentEquipment" class="mt-5 grid gap-4 border-y border-border py-4 sm:grid-cols-2">
|
||||
<dl class="mt-5 grid gap-4 border-y border-border py-4 sm:grid-cols-2">
|
||||
<div>
|
||||
<dt class="text-xs text-text-tertiary">资产</dt>
|
||||
<dd class="mt-1 text-sm font-medium text-text-primary">{{ currentEquipment.equipment_name }}</dd>
|
||||
<dd class="mt-1 font-mono text-xs text-text-tertiary">{{ currentEquipment.equipment_code }}</dd>
|
||||
<dd class="mt-1 text-sm font-medium text-text-primary">{{ disposalPrerequisite.name }}</dd>
|
||||
<dd class="mt-1 font-mono text-xs text-text-tertiary">{{ disposalPrerequisite.code }}</dd>
|
||||
</div>
|
||||
<div v-if="activeBorrowRecord">
|
||||
<div v-if="disposalPrerequisite.borrowTime && !disposalPreparationNotice">
|
||||
<dt class="text-xs text-text-tertiary">当前使用者</dt>
|
||||
<dd class="mt-1 text-sm font-medium text-text-primary">{{ currentBorrowerLabel }}</dd>
|
||||
<dd class="mt-1 text-xs text-text-tertiary">借出时间:{{ formatDateTime(activeBorrowRecord.borrow_time) }}</dd>
|
||||
<dd class="mt-1 text-sm font-medium text-text-primary">{{ disposalPrerequisite.borrower }}</dd>
|
||||
<dd class="mt-1 text-xs text-text-tertiary">借出时间:{{ formatDateTime(disposalPrerequisite.borrowTime) }}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
|
||||
<div v-if="canQuickReturnBeforeDisposal" class="mt-5 space-y-4">
|
||||
<div class="rounded-lg border border-status-warning/30 bg-status-warning/10 p-3">
|
||||
<p class="text-sm font-medium text-status-warning">确认实物已经收回后再继续</p>
|
||||
<p class="mt-1 text-xs leading-5 text-text-secondary">系统会结束当前未归还记录并完成入库,然后自动打开该资产的报废申请表。</p>
|
||||
</div>
|
||||
|
||||
<div v-if="disposalPrerequisite.borrowRecordId && !disposalReturnNeedsRefresh" class="mt-5 space-y-4">
|
||||
<div class="field-stack">
|
||||
<label class="field-label" for="disposal-return-condition">入库状况</label>
|
||||
<select id="disposal-return-condition" v-model="disposalReturnCondition" class="select">
|
||||
<select id="disposal-return-condition" v-model="disposalReturnCondition" class="select" :disabled="disposalReturnLoading">
|
||||
<option value="正常">正常</option>
|
||||
<option value="损坏">损坏</option>
|
||||
</select>
|
||||
@ -423,7 +418,14 @@
|
||||
<div class="mt-6 flex flex-col-reverse gap-3 sm:flex-row sm:justify-end">
|
||||
<button type="button" class="btn-secondary w-full sm:w-auto" :disabled="disposalReturnLoading" @click="closeDisposalPrerequisite">暂不处理</button>
|
||||
<button
|
||||
v-if="canQuickReturnBeforeDisposal"
|
||||
v-if="disposalReturnNeedsRefresh"
|
||||
type="button"
|
||||
class="btn-primary w-full sm:w-auto"
|
||||
:disabled="disposalReturnLoading"
|
||||
@click="refreshDisposalPrerequisite"
|
||||
>{{ disposalReturnLoading ? '正在刷新…' : '刷新并重新确认' }}</button>
|
||||
<button
|
||||
v-else-if="disposalPrerequisite.borrowRecordId"
|
||||
type="button"
|
||||
class="btn-primary w-full sm:w-auto"
|
||||
:disabled="disposalReturnLoading"
|
||||
@ -438,7 +440,7 @@
|
||||
|
||||
<!-- 报废申请弹窗 -->
|
||||
<div
|
||||
v-if="showDisposalForm && canApplyDisposal"
|
||||
v-if="showDisposalForm && disposalTreeItems[0]?.id === Number(route.params.id) && canApplyDisposal"
|
||||
class="sheet-backdrop"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
@ -470,6 +472,7 @@
|
||||
<span class="block truncate text-sm text-text-primary">{{ item.name }}</span>
|
||||
<span class="mt-1 block font-mono text-xs text-text-tertiary">{{ item.code }}</span>
|
||||
</span>
|
||||
<span class="shrink-0 text-sm tabular-nums text-text-secondary">{{ item.quantity === null ? '数量缺失' : item.quantity + ' 件' }}</span>
|
||||
<span v-if="item.isRoot" class="badge badge-neutral">主资产</span>
|
||||
</label>
|
||||
</div>
|
||||
@ -501,7 +504,16 @@
|
||||
<p v-if="disposalSubmitError" class="mt-4 text-sm text-status-error" role="alert">{{ disposalSubmitError }}</p>
|
||||
<div class="mt-6 flex flex-col-reverse gap-3 sm:flex-row sm:justify-end">
|
||||
<button type="button" class="btn-secondary w-full sm:w-auto" :disabled="disposalSubmitting" @click="showDisposalForm = false">取消</button>
|
||||
<button type="button" class="btn-danger w-full sm:w-auto" @click="submitDisposal" :disabled="!canSubmitDisposal || disposalSubmitting" :aria-busy="disposalSubmitting">
|
||||
<button
|
||||
v-if="disposalSubmitNeedsRefresh"
|
||||
type="button"
|
||||
class="btn-primary w-full sm:w-auto"
|
||||
:disabled="disposalSubmitting"
|
||||
@click="refreshDisposalApplication"
|
||||
>
|
||||
{{ disposalSubmitting ? '正在刷新…' : '刷新并重新核对' }}
|
||||
</button>
|
||||
<button v-else type="button" class="btn-danger w-full sm:w-auto" @click="submitDisposal" :disabled="!canSubmitDisposal || disposalSubmitting" :aria-busy="disposalSubmitting">
|
||||
{{ disposalSubmitting ? '正在提交...' : '提交申请' }}
|
||||
</button>
|
||||
</div>
|
||||
@ -526,11 +538,13 @@ import {
|
||||
getEquipmentDisposalHistory,
|
||||
createDisposal,
|
||||
returnEquipmentBeforeDisposal,
|
||||
type DisposalReturnCondition,
|
||||
type DisposalReturnChildrenDiff
|
||||
} from '@/api/disposal'
|
||||
import type {
|
||||
Equipment,
|
||||
EquipmentCurrentBorrow,
|
||||
EquipmentTreeNode,
|
||||
StorageLocation,
|
||||
AssetType,
|
||||
Department,
|
||||
@ -606,7 +620,6 @@ let bundleChildSeed = 0
|
||||
const maintenanceRecords = ref<any[]>([])
|
||||
const disposalRecords = ref<any[]>([])
|
||||
const showMaintenanceForm = ref(false)
|
||||
const showDisposalPrerequisite = ref(false)
|
||||
const showDisposalForm = ref(false)
|
||||
const showBarcodePrint = ref(false)
|
||||
type EquipmentDetail = Equipment & { borrow_records?: EquipmentCurrentBorrow[] }
|
||||
@ -619,15 +632,19 @@ const detailReady = computed(() => !isEdit.value || (
|
||||
!detailLoading.value && currentEquipment.value?.id === Number(route.params.id)
|
||||
))
|
||||
const selectedDisposalItemIds = ref<number[]>([])
|
||||
const disposalTreeItems = ref<DisposalTreeItem[]>([])
|
||||
const disposalPrerequisite = ref<DisposalPrerequisite | null>(null)
|
||||
const departmentTransferLoading = ref(false)
|
||||
const disposalReturnLoading = ref(false)
|
||||
const disposalReturnError = ref('')
|
||||
const disposalReturnCondition = ref<'正常' | '损坏'>('正常')
|
||||
const disposalReturnCondition = ref<DisposalReturnCondition>('正常')
|
||||
const disposalReturnNeedsRefresh = ref(false)
|
||||
const disposalReturnChildrenDiff = ref<DisposalReturnChildrenDiff | null>(null)
|
||||
const disposalReturnConfirmationToken = ref('')
|
||||
const disposalPreparationNotice = ref('')
|
||||
const disposalSubmitting = ref(false)
|
||||
const disposalSubmitError = ref('')
|
||||
const disposalSubmitNeedsRefresh = ref(false)
|
||||
|
||||
interface DisposalTreeItem {
|
||||
id: number
|
||||
@ -635,6 +652,19 @@ interface DisposalTreeItem {
|
||||
name: string
|
||||
depth: number
|
||||
isRoot: boolean
|
||||
quantity: number | null
|
||||
}
|
||||
|
||||
interface DisposalPrerequisite {
|
||||
id: number
|
||||
name: string
|
||||
code: string
|
||||
status: string
|
||||
title: string
|
||||
reason: string
|
||||
borrowRecordId?: number
|
||||
borrower: string
|
||||
borrowTime?: string
|
||||
}
|
||||
|
||||
const canCreate = computed(() => authStore.can(PERMISSIONS.ASSETS_CREATE))
|
||||
@ -751,28 +781,33 @@ const createDefaultFormState = (): EquipmentFormState => ({
|
||||
|
||||
const form = ref<EquipmentFormState>(createDefaultFormState())
|
||||
|
||||
const disposalTreeItems = computed<DisposalTreeItem[]>(() => {
|
||||
if (!currentEquipment.value) return []
|
||||
const snapshotDisposalTree = (root: EquipmentDetail): DisposalTreeItem[] => {
|
||||
const items: DisposalTreeItem[] = []
|
||||
const walk = (equipment: any, depth: number, isRoot = false) => {
|
||||
const walk = (equipment: EquipmentTreeNode, depth: number) => {
|
||||
const quantity = equipment.total_quantity
|
||||
items.push({
|
||||
id: Number(equipment.id),
|
||||
id: equipment.id,
|
||||
code: equipment.equipment_code || '-',
|
||||
name: equipment.equipment_name || equipment.equipment_type || '未命名资产',
|
||||
depth,
|
||||
isRoot
|
||||
isRoot: depth === 0,
|
||||
quantity: typeof quantity === 'number' && Number.isSafeInteger(quantity) && quantity > 0 ? quantity : null
|
||||
})
|
||||
;(equipment.children || []).forEach((child: any) => walk(child, depth + 1, false))
|
||||
equipment.children?.forEach((child) => walk(child, depth + 1))
|
||||
}
|
||||
walk(currentEquipment.value, 0, true)
|
||||
walk(root, 0)
|
||||
return items
|
||||
})
|
||||
}
|
||||
const confirmedDisposalQuantities = computed(() => disposalTreeItems.value.flatMap((item) =>
|
||||
item.quantity === null ? [] : [{ equipment_id: item.id, total_quantity: item.quantity }]
|
||||
))
|
||||
const unselectedMountedDisposalItems = computed(() =>
|
||||
disposalTreeItems.value.filter((item) => !item.isRoot && !selectedDisposalItemIds.value.includes(item.id))
|
||||
)
|
||||
const canSubmitDisposal = computed(() => Boolean(
|
||||
disposalForm.value.disposal_reason.trim() &&
|
||||
disposalTreeItems.value.length > 0 &&
|
||||
confirmedDisposalQuantities.value.length === disposalTreeItems.value.length &&
|
||||
unselectedMountedDisposalItems.value.length === 0
|
||||
))
|
||||
|
||||
@ -1112,13 +1147,17 @@ const submitMaintenance = async () => {
|
||||
|
||||
const beginDisposalForm = () => {
|
||||
if (!currentEquipment.value) return
|
||||
disposalPrerequisite.value = null
|
||||
disposalTreeItems.value = snapshotDisposalTree(currentEquipment.value)
|
||||
selectedDisposalItemIds.value = [currentEquipment.value.id]
|
||||
disposalSubmitError.value = ''
|
||||
disposalSubmitNeedsRefresh.value = false
|
||||
showDisposalForm.value = true
|
||||
}
|
||||
|
||||
const resetDisposalPrerequisite = () => {
|
||||
disposalReturnError.value = ''
|
||||
disposalReturnNeedsRefresh.value = false
|
||||
disposalReturnCondition.value = '正常'
|
||||
disposalReturnChildrenDiff.value = null
|
||||
disposalReturnConfirmationToken.value = ''
|
||||
@ -1126,69 +1165,132 @@ const resetDisposalPrerequisite = () => {
|
||||
|
||||
const closeDisposalPrerequisite = () => {
|
||||
if (disposalReturnLoading.value) return
|
||||
showDisposalPrerequisite.value = false
|
||||
disposalPrerequisite.value = null
|
||||
resetDisposalPrerequisite()
|
||||
}
|
||||
|
||||
const openDisposalForm = () => {
|
||||
if (!canApplyDisposal.value || !currentEquipment.value) return
|
||||
disposalPreparationNotice.value = ''
|
||||
if (!canStartDisposal.value) {
|
||||
resetDisposalPrerequisite()
|
||||
showDisposalPrerequisite.value = true
|
||||
const showDisposalApplicationOrPrerequisite = () => {
|
||||
const equipment = currentEquipment.value
|
||||
if (!detailReady.value || !canApplyDisposal.value || !equipment) return
|
||||
resetDisposalPrerequisite()
|
||||
if (canStartDisposal.value) {
|
||||
beginDisposalForm()
|
||||
return
|
||||
}
|
||||
beginDisposalForm()
|
||||
disposalPreparationNotice.value = ''
|
||||
disposalPrerequisite.value = {
|
||||
id: equipment.id,
|
||||
name: equipment.equipment_name,
|
||||
code: equipment.equipment_code,
|
||||
status: equipment.status,
|
||||
title: disposalPrerequisiteTitle.value,
|
||||
reason: disposalBlockReason.value,
|
||||
borrowRecordId: canQuickReturnBeforeDisposal.value ? activeBorrowRecord.value?.id : undefined,
|
||||
borrower: currentBorrowerLabel.value,
|
||||
borrowTime: activeBorrowRecord.value?.borrow_time
|
||||
}
|
||||
}
|
||||
|
||||
const openDisposalForm = () => {
|
||||
disposalPreparationNotice.value = ''
|
||||
showDisposalApplicationOrPrerequisite()
|
||||
}
|
||||
|
||||
const refreshDisposalPrerequisite = async () => {
|
||||
const equipmentId = disposalPrerequisite.value?.id
|
||||
if (equipmentId !== Number(route.params.id) || disposalReturnLoading.value) return
|
||||
disposalReturnLoading.value = true
|
||||
try {
|
||||
await fetchEquipmentData(true)
|
||||
if (equipmentId !== Number(route.params.id)) return
|
||||
await Promise.all([fetchDisposalRecords(), fetchMaintenanceRecords()])
|
||||
if (equipmentId === Number(route.params.id)) showDisposalApplicationOrPrerequisite()
|
||||
} catch {
|
||||
disposalReturnError.value = '刷新资产失败,请重试。'
|
||||
} finally {
|
||||
disposalReturnLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const submitReturnBeforeDisposal = async () => {
|
||||
if (!currentEquipment.value || !canQuickReturnBeforeDisposal.value || disposalReturnLoading.value) return
|
||||
const snapshot = disposalPrerequisite.value
|
||||
if (!snapshot?.borrowRecordId || snapshot.id !== Number(route.params.id) ||
|
||||
disposalReturnLoading.value || disposalReturnNeedsRefresh.value) return
|
||||
const condition = disposalReturnCondition.value
|
||||
disposalReturnLoading.value = true
|
||||
disposalReturnError.value = ''
|
||||
try {
|
||||
const response = await returnEquipmentBeforeDisposal(currentEquipment.value.id, {
|
||||
return_condition: disposalReturnCondition.value,
|
||||
const response = await returnEquipmentBeforeDisposal(snapshot.id, {
|
||||
borrow_record_id: snapshot.borrowRecordId,
|
||||
return_condition: condition,
|
||||
confirmation_token: disposalReturnConfirmationToken.value || undefined
|
||||
})
|
||||
if (snapshot.id !== Number(route.params.id)) return
|
||||
if (response.data?.need_confirm) {
|
||||
disposalReturnChildrenDiff.value = response.data.children_diff || { removed: [], added: [] }
|
||||
disposalReturnConfirmationToken.value = response.data.confirmation_token || ''
|
||||
return
|
||||
}
|
||||
|
||||
resetDisposalPrerequisite()
|
||||
disposalReturnNeedsRefresh.value = true
|
||||
disposalPreparationNotice.value = condition === '损坏' ? '资产已按损坏入库。' : '资产已入库。'
|
||||
await fetchEquipmentData(true)
|
||||
if (currentEquipment.value?.status !== '可用') {
|
||||
throw new Error('资产已完成入库,但当前状态尚未恢复为可用,请刷新后重试。')
|
||||
}
|
||||
showDisposalPrerequisite.value = false
|
||||
disposalReturnChildrenDiff.value = null
|
||||
disposalReturnConfirmationToken.value = ''
|
||||
disposalPreparationNotice.value = '资产已入库,可以继续填写并提交报废申请。'
|
||||
beginDisposalForm()
|
||||
if (snapshot.id !== Number(route.params.id)) return
|
||||
if (canStartDisposal.value) beginDisposalForm()
|
||||
else disposalReturnError.value = disposalBlockReason.value
|
||||
} catch (error: any) {
|
||||
disposalReturnError.value = error?.message || '资产入库失败,请核对当前借用记录后重试。'
|
||||
if (snapshot.id !== Number(route.params.id)) return
|
||||
if (disposalPreparationNotice.value) {
|
||||
disposalReturnError.value = '资产详情刷新失败,请刷新后继续。'
|
||||
} else {
|
||||
disposalReturnError.value = error?.message || '资产入库失败,请重试。'
|
||||
if (error?.status === 409) disposalReturnNeedsRefresh.value = true
|
||||
}
|
||||
} finally {
|
||||
disposalReturnLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const toggleDisposalItem = (id: number) => {
|
||||
if (currentEquipment.value?.id === id) return
|
||||
if (disposalTreeItems.value[0]?.id === id || disposalSubmitting.value) return
|
||||
selectedDisposalItemIds.value = selectedDisposalItemIds.value.includes(id)
|
||||
? selectedDisposalItemIds.value.filter((itemId) => itemId !== id)
|
||||
: [...selectedDisposalItemIds.value, id]
|
||||
}
|
||||
|
||||
const refreshDisposalApplication = async () => {
|
||||
const equipmentId = disposalTreeItems.value[0]?.id
|
||||
if (equipmentId !== Number(route.params.id) || disposalSubmitting.value) return
|
||||
disposalSubmitting.value = true
|
||||
try {
|
||||
await fetchEquipmentData(true)
|
||||
if (equipmentId !== Number(route.params.id)) return
|
||||
await Promise.all([fetchDisposalRecords(), fetchMaintenanceRecords()])
|
||||
if (equipmentId !== Number(route.params.id)) return
|
||||
if (canStartDisposal.value) beginDisposalForm()
|
||||
else disposalSubmitError.value = disposalBlockReason.value
|
||||
} catch {
|
||||
disposalSubmitError.value = '刷新资产失败,请重试。'
|
||||
} finally {
|
||||
disposalSubmitting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const submitDisposal = async () => {
|
||||
if (!canSubmitDisposal.value || disposalSubmitting.value) return
|
||||
const equipmentId = disposalTreeItems.value[0]?.id
|
||||
if (!canSubmitDisposal.value || disposalSubmitting.value || disposalSubmitNeedsRefresh.value ||
|
||||
equipmentId !== Number(route.params.id)) return
|
||||
disposalSubmitting.value = true
|
||||
disposalSubmitError.value = ''
|
||||
try {
|
||||
const response = await createDisposal({
|
||||
equipment_id: Number(route.params.id),
|
||||
equipment_id: equipmentId,
|
||||
item_ids: selectedDisposalItemIds.value,
|
||||
confirmed_quantities: confirmedDisposalQuantities.value,
|
||||
...disposalForm.value
|
||||
})
|
||||
if (equipmentId !== Number(route.params.id)) return
|
||||
showDisposalForm.value = false
|
||||
disposalForm.value = { disposal_reason: '', disposal_method: '报废', estimated_value: 0, notes: '' }
|
||||
selectedDisposalItemIds.value = []
|
||||
@ -1199,6 +1301,7 @@ const submitDisposal = async () => {
|
||||
if (disposalId) await router.push(`/workflows/disposals/${disposalId}`)
|
||||
} catch (error: any) {
|
||||
disposalSubmitError.value = error?.message || '提交报废申请失败,请检查填写内容后重试。'
|
||||
if (error?.status === 409) disposalSubmitNeedsRefresh.value = true
|
||||
} finally {
|
||||
disposalSubmitting.value = false
|
||||
}
|
||||
@ -1210,7 +1313,7 @@ const getDisposalStatusClass = (status: string) => {
|
||||
}
|
||||
|
||||
const getDisposalStatusText = (status: string) => {
|
||||
const map: Record<string, string> = { pending: '待审批', approved: '已审批', rejected: '已驳回', completed: '已完成' }
|
||||
const map: Record<string, string> = { pending: '待审批', approved: '已审批', rejected: '已驳回', completed: '已完成', cancelled: '已撤销' }
|
||||
return map[status] || status
|
||||
}
|
||||
|
||||
|
||||
@ -61,6 +61,7 @@
|
||||
<option value="approved">已审批</option>
|
||||
<option value="rejected">已驳回</option>
|
||||
<option value="completed">已完成</option>
|
||||
<option value="cancelled">已撤销</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="field-stack">
|
||||
@ -600,7 +601,8 @@ const getStatusText = (status: string) => {
|
||||
pending: '待审批',
|
||||
approved: '已审批',
|
||||
rejected: '已驳回',
|
||||
completed: '已完成'
|
||||
completed: '已完成',
|
||||
cancelled: '已撤销'
|
||||
}
|
||||
return map[status] || status
|
||||
}
|
||||
|
||||
@ -69,7 +69,7 @@
|
||||
<section class="card">
|
||||
<div class="list-header">
|
||||
<h3 class="section-title">报废资产明细</h3>
|
||||
<span class="badge badge-neutral">申请后关系已锁定</span>
|
||||
<span v-if="record.status === 'pending' || record.status === 'approved'" class="badge badge-neutral">申请后关系已锁定</span>
|
||||
</div>
|
||||
<div class="space-y-3">
|
||||
<div v-for="({ item, quantity, fromSnapshot }, index) in disposalItems" :key="item.id || item.equipment_id" class="panel flex items-center justify-between gap-4">
|
||||
@ -158,6 +158,20 @@
|
||||
<button type="button" class="btn-primary" :disabled="submitting || !completeForm.completion_notes" @click="submitCompletion">完成报废</button>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="canCancel" class="mt-4 border-t border-border pt-4">
|
||||
<button v-if="!showCancelForm" type="button" class="btn-secondary" :disabled="submitting" @click="showCancelForm = true">
|
||||
撤销申请
|
||||
</button>
|
||||
<form v-else class="field-stack" @submit.prevent="submitCancellation">
|
||||
<p class="text-sm text-status-warning">仅限实物尚未处置</p>
|
||||
<label class="field-label" for="disposal-cancel-reason">撤销原因</label>
|
||||
<textarea id="disposal-cancel-reason" v-model.trim="cancelReason" class="input" rows="2" :disabled="submitting"></textarea>
|
||||
<div class="flex flex-wrap justify-end gap-2">
|
||||
<button type="button" class="btn-secondary" :disabled="submitting" @click="showCancelForm = false">返回</button>
|
||||
<button type="submit" class="btn-danger" :disabled="submitting || !cancelReason">确认撤销</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
</div>
|
||||
@ -168,6 +182,7 @@ import { computed, onMounted, ref } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import {
|
||||
approveDisposal,
|
||||
cancelDisposal,
|
||||
completeDisposal,
|
||||
getDisposalDetail,
|
||||
type ConfirmedDisposalQuantity,
|
||||
@ -187,17 +202,20 @@ const loading = ref(false)
|
||||
const submitting = ref(false)
|
||||
const errorText = ref('')
|
||||
const rejectReason = ref('')
|
||||
const showCancelForm = ref(false)
|
||||
const cancelReason = ref('')
|
||||
const completeForm = ref({ actual_value: 0, completion_notes: '' })
|
||||
|
||||
const canApprove = computed(() => authStore.can(PERMISSIONS.DISPOSALS_APPROVE))
|
||||
const canComplete = computed(() => authStore.can(PERMISSIONS.DISPOSALS_COMPLETE))
|
||||
const canApproveRecord = computed(() => canApprove.value)
|
||||
const canCancel = computed(() => record.value?.status === 'approved' && canApprove.value)
|
||||
const needsApprovedQuantityCheck = computed(() =>
|
||||
record.value?.status === 'approved' && record.value.requires_quantity_confirmation === true
|
||||
)
|
||||
const showActions = computed(() =>
|
||||
(record.value?.status === 'pending' && canApproveRecord.value) ||
|
||||
(record.value?.status === 'approved' && (canComplete.value || (needsApprovedQuantityCheck.value && canApprove.value)))
|
||||
(record.value?.status === 'approved' && (canComplete.value || canCancel.value))
|
||||
)
|
||||
const parseQuantity = (value: unknown): number | null =>
|
||||
typeof value === 'number' && Number.isSafeInteger(value) && value > 0 ? value : null
|
||||
@ -301,6 +319,23 @@ const submitCompletion = async () => {
|
||||
|
||||
const getItemName = (item: DisposalItem) => item.equipment_name || item.equipment?.equipment_name || item.equipment_type || '未命名资产'
|
||||
|
||||
const submitCancellation = async () => {
|
||||
const id = record.value?.id
|
||||
if (!canCancel.value || id !== Number(route.params.id) || submitting.value || !cancelReason.value.trim()) return
|
||||
submitting.value = true
|
||||
try {
|
||||
await cancelDisposal(id, { cancel_reason: cancelReason.value.trim() })
|
||||
showCancelForm.value = false
|
||||
cancelReason.value = ''
|
||||
await loadDetail()
|
||||
} catch (error: any) {
|
||||
alert(error?.message || '撤销失败,请核对申请状态后重试')
|
||||
await loadDetail()
|
||||
} finally {
|
||||
submitting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const getActionText = (action: DisposalAction) => {
|
||||
const type = action.action_type || action.action || ''
|
||||
const map: Record<string, string> = {
|
||||
@ -314,6 +349,7 @@ const getActionText = (action: DisposalAction) => {
|
||||
rejected: '驳回申请',
|
||||
complete: '完成报废',
|
||||
completed: '完成报废',
|
||||
cancelled: '撤销申请',
|
||||
legacy_imported: '历史记录补录'
|
||||
}
|
||||
return map[type] || type || `${action.from_status || '-'} → ${action.to_status || '-'}`
|
||||
@ -330,7 +366,8 @@ const getStatusText = (status: string) => ({
|
||||
pending: '待审批',
|
||||
approved: '已审批',
|
||||
rejected: '已驳回',
|
||||
completed: '已完成'
|
||||
completed: '已完成',
|
||||
cancelled: '已撤销'
|
||||
}[status] || status)
|
||||
|
||||
const formatCurrency = (value?: number) => `¥${Number(value || 0).toFixed(2)}`
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user