Add opt-in automatic return for batch disposal
This commit is contained in:
parent
a19e64d25c
commit
08484c1058
@ -10,9 +10,12 @@ test('批量报废在本机隔离 MySQL 验证完整资产树、事务和审批
|
||||
&& 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 { borrowEquipment, returnEquipment } = await import('../borrowController')
|
||||
const prefix = `disp-${randomUUID().slice(0, 12)}`
|
||||
const userIds: number[] = []
|
||||
const personIds: number[] = []
|
||||
const departmentIds: number[] = []
|
||||
const storageIds: number[] = []
|
||||
const env = { YYD_NOTIFICATION_SEND_ENABLED: 'true', YYD_NOTIFICATION_SEND_FULL_ROLLOUT: 'true' }
|
||||
const previousEnv = Object.fromEntries(Object.keys(env).map(key => [key, process.env[key]]))
|
||||
Object.assign(process.env, env)
|
||||
@ -38,6 +41,7 @@ test('批量报废在本机隔离 MySQL 验证完整资产树、事务和审批
|
||||
return state
|
||||
}
|
||||
const submit = (assets: { equipment_id: number; item_ids: number[];
|
||||
auto_return_token?: string;
|
||||
confirmed_quantities?: { equipment_id: number; total_quantity: number }[] }[], ip?: string) => call(createBatchDisposal,
|
||||
{ assets, disposal_reason: '设备老化', disposal_method: '报废', notes: '本机验证' }, ip)
|
||||
|
||||
@ -148,6 +152,138 @@ test('批量报废在本机隔离 MySQL 验证完整资产树、事务和审批
|
||||
const repeated = await submit([{ equipment_id: root.id, item_ids: [root.id, child.id, nested.id] }])
|
||||
assert.equal(repeated.status, 409)
|
||||
})
|
||||
|
||||
const borrow = async (equipmentId: number) => {
|
||||
const response = await call(borrowEquipment, { equipment_id: equipmentId, person_id: person.id, is_long_term: true })
|
||||
assert.equal(response.status, 200, JSON.stringify(response.body))
|
||||
return response.body.data.id as number
|
||||
}
|
||||
const previewReturn = async (...equipmentIds: number[]) => {
|
||||
const response = await call(previewBatchDisposal, { equipment_ids: equipmentIds })
|
||||
assert.equal(response.status, 200, JSON.stringify(response.body))
|
||||
return response.body.data.candidates
|
||||
}
|
||||
const pendingNotices = () => prisma.notification.count({ where: { type: 'disposal', metadata: { contains: prefix } } })
|
||||
|
||||
await t.test('只归还明确选中的借用,配件、原库位及报废申请在同一事务处理', async () => {
|
||||
const department = await prisma.department.create({ data: { name: prefix, source_system: 'ding_hr_business' } })
|
||||
departmentIds.push(department.id)
|
||||
await prisma.person.update({ where: { id: person.id }, data: { main_department_id: department.id } })
|
||||
const location = await prisma.storageLocation.create({ data: { name: prefix } })
|
||||
storageIds.push(location.id)
|
||||
const checkedOut = await prisma.equipment.create({ data: { ...data('auto-root'), storage_location_id: location.id } })
|
||||
const accessory = await prisma.equipment.create({ data: { ...data('auto-part', checkedOut.id), storage_location_id: location.id } })
|
||||
const another = await prisma.equipment.create({ data: data('auto-another') })
|
||||
const unselected = await prisma.equipment.create({ data: data('auto-unselected') })
|
||||
const ready = await prisma.equipment.create({ data: data('auto-ready') })
|
||||
const borrowedId = await borrow(checkedOut.id)
|
||||
const anotherBorrowId = await borrow(another.id)
|
||||
const unselectedBorrowId = await borrow(unselected.id)
|
||||
const [offered, offeredAnother, offeredUnselected, available] = await previewReturn(checkedOut.id, another.id, unselected.id, ready.id)
|
||||
for (const candidate of [offered, offeredAnother, offeredUnselected]) {
|
||||
assert.match(candidate.blocked_reason, /已借出/)
|
||||
assert.match(candidate.auto_return_token, /^[a-f0-9]{64}$/)
|
||||
}
|
||||
assert.equal(available.auto_return_token, undefined)
|
||||
assert.equal(available.blocked_reason, null)
|
||||
assert.deepEqual(offered.items.map((item: { id: number }) => item.id), [checkedOut.id, accessory.id])
|
||||
|
||||
const selection = (candidate: any) => ({
|
||||
equipment_id: candidate.equipment_id, item_ids: candidate.items.map((item: { id: number }) => item.id),
|
||||
auto_return_token: candidate.auto_return_token
|
||||
})
|
||||
const selected = [selection(offered), selection(available), selection(offeredAnother)]
|
||||
const noConsent = await submit([{ equipment_id: checkedOut.id, item_ids: [checkedOut.id, accessory.id] }])
|
||||
assert.equal(noConsent.status, 409)
|
||||
assert.match(noConsent.body.message, /已借出/)
|
||||
const malformed = await submit([{ ...selected[0], auto_return_token: 'not-a-token' }])
|
||||
assert.equal(malformed.status, 422)
|
||||
const omittedAccessory = await submit([{ ...selected[0], item_ids: [checkedOut.id] }])
|
||||
assert.equal(omittedAccessory.status, 409)
|
||||
assert.match(omittedAccessory.body.message, new RegExp(accessory.equipment_code))
|
||||
|
||||
const noticeCount = await pendingNotices()
|
||||
const disposalIds = { in: [checkedOut.id, another.id, ready.id] }
|
||||
const borrowIds = { in: [borrowedId, anotherBorrowId, unselectedBorrowId] }
|
||||
const returnedRoots = { in: [checkedOut.id, another.id] }
|
||||
const failed = await submit(selected, 'x'.repeat(60))
|
||||
assert.equal(failed.status, 422)
|
||||
assert.match(failed.body.message, /ip_address/)
|
||||
assert.equal(await prisma.disposalRecord.count({ where: { equipment_id: disposalIds } }), 0)
|
||||
assert.equal(await prisma.assetTransferRecord.count({ where: { root_equipment_id: returnedRoots, action_type: 'return' } }), 0)
|
||||
assert.equal(await prisma.borrowRecord.count({ where: { id: borrowIds, status: '已借出', return_time: null } }), 3)
|
||||
assert.equal(await pendingNotices(), noticeCount)
|
||||
const rolledBackRoot = await prisma.equipment.findUniqueOrThrow({ where: { id: checkedOut.id } })
|
||||
assert.deepEqual([rolledBackRoot.status, rolledBackRoot.department_id, rolledBackRoot.remaining_quantity], ['已借出', department.id, 0])
|
||||
|
||||
const succeeded = await submit(selected)
|
||||
assert.equal(succeeded.status, 200, JSON.stringify(succeeded.body))
|
||||
const ids = succeeded.body.data.disposal_ids as number[]
|
||||
assert.equal(ids.length, 3)
|
||||
assert.equal(await prisma.disposalRecord.count({ where: { id: { in: ids }, status: 'pending' } }), 3)
|
||||
assert.equal(await pendingNotices(), noticeCount + 1)
|
||||
const returned = await prisma.borrowRecord.findMany({ where: { id: borrowIds }, orderBy: { id: 'asc' } })
|
||||
assert.deepEqual(returned.map(row => [row.status, row.return_time !== null, row.return_condition]), [
|
||||
['已归还', true, '正常'], ['已归还', true, '正常'], ['已借出', false, '正常']
|
||||
])
|
||||
const movement = await prisma.assetTransferRecord.findMany({
|
||||
where: { root_equipment_id: returnedRoots, action_type: 'return', operated_by: applicant.id },
|
||||
include: { items: true }, orderBy: { root_equipment_id: 'asc' }
|
||||
})
|
||||
assert.equal(movement.length, 2)
|
||||
assert.deepEqual(new Set(movement[0].items.map(item => item.equipment_id)), new Set([checkedOut.id, accessory.id]))
|
||||
assert.equal(movement[0].reason, '批量报废前归还入库')
|
||||
const returnedTree = await prisma.equipment.findMany({ where: { id: { in: [checkedOut.id, accessory.id] } }, orderBy: { id: 'asc' } })
|
||||
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]
|
||||
])
|
||||
})
|
||||
|
||||
await t.test('还后重借、配件变动、缺失或损坏的配件快照均不能使用旧确认归还', async () => {
|
||||
const reborrowed = await prisma.equipment.create({ data: data('reborrowed') })
|
||||
const firstBorrow = await borrow(reborrowed.id)
|
||||
const [firstOffer] = await previewReturn(reborrowed.id)
|
||||
assert.ok(firstOffer.auto_return_token)
|
||||
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 nextBorrow = await borrow(reborrowed.id)
|
||||
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 }])
|
||||
assert.equal(stale.status, 409)
|
||||
assert.match(stale.body.message, /重新预检/)
|
||||
const freshRecord = await prisma.borrowRecord.findUniqueOrThrow({ where: { id: nextBorrow } })
|
||||
assert.deepEqual([freshRecord.status, freshRecord.return_time], ['已借出', null])
|
||||
assert.equal(await prisma.disposalRecord.count({ where: { equipment_id: reborrowed.id } }), 0)
|
||||
|
||||
const changingRoot = await prisma.equipment.create({ data: data('changed-root') })
|
||||
const originalPart = await prisma.equipment.create({ data: data('original-part', changingRoot.id) })
|
||||
const changingBorrowId = await borrow(changingRoot.id)
|
||||
const [valid] = await previewReturn(changingRoot.id)
|
||||
assert.ok(valid.auto_return_token)
|
||||
const originalBorrow = await prisma.borrowRecord.findUniqueOrThrow({ where: { id: changingBorrowId } })
|
||||
for (const snapshot of [null, '{']) {
|
||||
await prisma.borrowRecord.update({ where: { id: changingBorrowId }, data: { children_snapshot: snapshot } })
|
||||
const [blocked] = await previewReturn(changingRoot.id)
|
||||
assert.match(blocked.blocked_reason, /已借出/)
|
||||
assert.equal(blocked.auto_return_token, undefined)
|
||||
}
|
||||
await prisma.borrowRecord.update({ where: { id: changingBorrowId }, data: { children_snapshot: originalBorrow.children_snapshot } })
|
||||
const [beforeMount] = await previewReturn(changingRoot.id)
|
||||
assert.ok(beforeMount.auto_return_token)
|
||||
const attached = await prisma.equipment.create({ data: {
|
||||
...data('added-part', changingRoot.id), status: '已借出', remaining_quantity: 0
|
||||
} })
|
||||
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 }])
|
||||
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)
|
||||
})
|
||||
} finally {
|
||||
for (const [key, value] of Object.entries(previousEnv)) {
|
||||
if (value === undefined) delete process.env[key]
|
||||
@ -165,10 +301,13 @@ test('批量报废在本机隔离 MySQL 验证完整资产树、事务和审批
|
||||
await tx.disposalRecord.deleteMany({ where: { id: { in: disposalIds } } })
|
||||
await tx.borrowRecord.deleteMany({ where: { equipment_id } })
|
||||
await tx.maintenanceRecord.deleteMany({ where: { equipment_id } })
|
||||
await tx.assetTransferRecord.deleteMany({ where: { root_equipment_id: equipment_id } })
|
||||
await tx.equipment.updateMany({ where: { id: equipment_id }, data: { parent_id: null } })
|
||||
await tx.equipment.deleteMany({ where: { id: equipment_id } })
|
||||
await tx.user.deleteMany({ where: { id: { in: userIds } } })
|
||||
await tx.person.deleteMany({ where: { id: { in: personIds } } })
|
||||
await tx.department.deleteMany({ where: { id: { in: departmentIds } } })
|
||||
await tx.storageLocation.deleteMany({ where: { id: { in: storageIds } } })
|
||||
}, { timeout: 20000 })
|
||||
} finally { await prisma.$disconnect() }
|
||||
}
|
||||
|
||||
@ -5,9 +5,11 @@ import { successResponse, errorResponse } from '../utils/response'
|
||||
import { logOperation } from './operationLogController'
|
||||
import { calculateEquipmentValues } from '../utils/assetValue'
|
||||
import { loadAndLockAssetTree, lockEquipmentRows } from '../services/assetMovementService'
|
||||
import { completeLockedBorrowReturn } from '../services/borrowReturnService'
|
||||
import {
|
||||
assertDisposalItemsConfirmed, DisposalConflictError, disposalTreeSelect, getDisposalBlockedReason,
|
||||
getDisposalOccupancy, loadDisposalTrees, MAX_DISPOSAL_BATCH_ROOTS, type DisposalTreeItem
|
||||
assertDisposalItemsConfirmed, DisposalConflictError, disposalTreeSelect, getDisposalAutoReturn, getDisposalBlockedReason,
|
||||
getDisposalOccupancy, isDisposalAutoReturnRoot, loadDisposalAutoReturnBorrows, loadDisposalTrees,
|
||||
MAX_DISPOSAL_BATCH_ROOTS, type DisposalTreeItem
|
||||
} from '../utils/disposalSubmission'
|
||||
import {
|
||||
createBusinessNotification,
|
||||
@ -436,13 +438,18 @@ export const previewBatchDisposal = async (req: Request, res: Response) => {
|
||||
const trees = await loadDisposalTrees(prisma, roots)
|
||||
const treeIds = [...new Set([...trees.values()].flatMap(tree => tree.map(item => item.id)))]
|
||||
const occupancy = treeIds.length ? await getDisposalOccupancy(prisma, treeIds) : undefined
|
||||
const returnIds = [...new Set(roots.filter(isDisposalAutoReturnRoot)
|
||||
.flatMap(root => trees.get(root.id)!.map(item => item.id)))]
|
||||
const returnBorrows = await loadDisposalAutoReturnBorrows(prisma, returnIds)
|
||||
const candidates = distinctInputs.map(({ label, root }) => {
|
||||
const tree = root ? trees.get(root.id)! : []
|
||||
const autoReturn = root && occupancy ? getDisposalAutoReturn(tree, occupancy, returnBorrows) : undefined
|
||||
return {
|
||||
equipment_id: root?.id ?? null, equipment_code: root?.equipment_code ?? label,
|
||||
equipment_name: root?.equipment_name ?? '', status: root?.status ?? '未找到',
|
||||
items: tree.map(({ id, equipment_code, equipment_name, total_quantity }) => ({ id, equipment_code, equipment_name, total_quantity })),
|
||||
blocked_reason: root ? getDisposalBlockedReason(tree, occupancy) : '未找到资产'
|
||||
blocked_reason: root ? getDisposalBlockedReason(tree, occupancy) : '未找到资产',
|
||||
...(autoReturn ? { auto_return_token: autoReturn.token } : {})
|
||||
}
|
||||
})
|
||||
successResponse(res, { candidates, duplicate_codes: [...duplicateCodes.values()] }, '批量预检完成')
|
||||
@ -461,7 +468,7 @@ 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> }>()
|
||||
const confirmed = new Map<number, { itemIds: number[]; quantities?: Map<number, number>; autoReturnToken?: string }>()
|
||||
const lockedIds = new Set<number>()
|
||||
for (const asset of assets) {
|
||||
if (!isEquipmentId(asset?.equipment_id) || !Array.isArray(asset.item_ids) ||
|
||||
@ -469,6 +476,10 @@ export const createBatchDisposal = async (req: Request, res: Response) => {
|
||||
return errorResponse(res, '请逐项确认报废明细,明细必须包含主资产', 422)
|
||||
}
|
||||
if (confirmed.has(asset.equipment_id)) return errorResponse(res, '批量报废包含重复主资产', 422)
|
||||
if (asset.auto_return_token !== undefined &&
|
||||
(typeof asset.auto_return_token !== 'string' || !/^[a-f0-9]{64}$/.test(asset.auto_return_token))) {
|
||||
return errorResponse(res, '自动归还确认凭据无效,请重新预检', 422)
|
||||
}
|
||||
for (const id of asset.item_ids as number[]) {
|
||||
if (lockedIds.has(id)) return errorResponse(res, '批量报废明细包含重复资产', 422)
|
||||
lockedIds.add(id)
|
||||
@ -476,6 +487,7 @@ 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,
|
||||
quantities: asset.confirmed_quantities === undefined
|
||||
? undefined : readConfirmedDisposalQuantities(asset.confirmed_quantities)
|
||||
})
|
||||
@ -487,16 +499,40 @@ export const createBatchDisposal = async (req: Request, res: Response) => {
|
||||
await lockEquipmentRows(tx, [...lockedIds])
|
||||
const roots = await tx.equipment.findMany({ where: { id: { in: rootIds } }, select: disposalTreeSelect })
|
||||
if (roots.length !== rootIds.length) throw new DisposalConflictError('有主资产已不存在,请重新预检')
|
||||
const trees = await loadDisposalTrees(tx, roots)
|
||||
let trees = await loadDisposalTrees(tx, roots)
|
||||
for (const id of rootIds) {
|
||||
const tree = trees.get(id)!
|
||||
const blocked = getDisposalBlockedReason(tree)
|
||||
if (blocked) throw new DisposalConflictError(`${tree[0].equipment_code}:${blocked}`)
|
||||
const confirmation = confirmed.get(id)!
|
||||
if (!confirmation.autoReturnToken) {
|
||||
const blocked = getDisposalBlockedReason(tree)
|
||||
if (blocked) throw new DisposalConflictError(`${tree[0].equipment_code}:${blocked}`)
|
||||
}
|
||||
assertDisposalItemsConfirmed(tree, confirmation.itemIds)
|
||||
if (confirmation.quantities) assertConfirmedDisposalQuantities(tree, confirmation.quantities)
|
||||
}
|
||||
const occupancy = await getDisposalOccupancy(tx, [...lockedIds])
|
||||
let occupancy = await getDisposalOccupancy(tx, [...lockedIds])
|
||||
const returnRoots = rootIds.filter(id => confirmed.get(id)!.autoReturnToken)
|
||||
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) {
|
||||
throw new DisposalConflictError(`${items[0].equipment_code}:借用或资产状态已变化,请重新预检后确认归还`)
|
||||
}
|
||||
return { items, borrowRecord: eligible.record }
|
||||
})
|
||||
for (const { items, borrowRecord } of returns) {
|
||||
await completeLockedBorrowReturn(tx, {
|
||||
items, borrowRecord, returnCondition: '正常', operatedBy: userId,
|
||||
reason: '批量报废前归还入库', requireUnreturned: true
|
||||
})
|
||||
}
|
||||
const returnedRoots = await tx.equipment.findMany({ where: { id: { in: rootIds } }, select: disposalTreeSelect })
|
||||
trees = await loadDisposalTrees(tx, returnedRoots)
|
||||
occupancy = await getDisposalOccupancy(tx, [...lockedIds])
|
||||
}
|
||||
for (const id of rootIds) {
|
||||
const tree = trees.get(id)!
|
||||
const blocked = getDisposalBlockedReason(tree, occupancy)
|
||||
|
||||
@ -1,9 +1,10 @@
|
||||
import type { Prisma } from '@prisma/client'
|
||||
import { Prisma } from '@prisma/client'
|
||||
import { buildReturnConfirmationToken, getReturnChildrenDiff } from './returnSnapshot'
|
||||
|
||||
export const MAX_DISPOSAL_BATCH_ROOTS = 500
|
||||
|
||||
export const disposalTreeSelect = {
|
||||
id: true, equipment_code: true, equipment_name: true, parent_id: true,
|
||||
id: true, equipment_code: true, equipment_name: true, equipment_model: true, equipment_type: true, parent_id: true,
|
||||
department_id: true, storage_location_id: true, status: true, mount_status: true,
|
||||
total_quantity: true, remaining_quantity: true, unit_price: true, updated_at: true
|
||||
} as const
|
||||
@ -68,6 +69,64 @@ export const getDisposalOccupancy = async (client: Prisma.TransactionClient, ids
|
||||
}
|
||||
}
|
||||
|
||||
type DisposalBorrow = {
|
||||
id: number
|
||||
equipment_id: number
|
||||
person_id: number
|
||||
return_time: Date | null
|
||||
children_snapshot: string | null
|
||||
updated_at: Date
|
||||
}
|
||||
|
||||
export const isDisposalAutoReturnRoot = (root: DisposalTreeItem) =>
|
||||
root.parent_id === null && root.mount_status !== 'mounted' &&
|
||||
root.status === '已借出' && root.total_quantity === 1 && root.remaining_quantity === 0
|
||||
|
||||
export const loadDisposalAutoReturnBorrows = async (
|
||||
client: Prisma.TransactionClient, ids: number[], lock = false
|
||||
) => {
|
||||
const byAsset = new Map<number, DisposalBorrow[]>()
|
||||
if (!ids.length) return byAsset
|
||||
const rows = await client.$queryRaw<DisposalBorrow[]>(Prisma.sql`
|
||||
SELECT id, equipment_id, person_id, return_time, children_snapshot, updated_at
|
||||
FROM borrow_record
|
||||
WHERE equipment_id IN (${Prisma.join(ids)}) AND status = ${'已借出'}
|
||||
ORDER BY id ${lock ? Prisma.sql`FOR UPDATE` : Prisma.empty}
|
||||
`)
|
||||
for (const row of rows) {
|
||||
const group = byAsset.get(row.equipment_id)
|
||||
if (group) group.push(row)
|
||||
else byAsset.set(row.equipment_id, [row])
|
||||
}
|
||||
return byAsset
|
||||
}
|
||||
|
||||
export const getDisposalAutoReturn = (
|
||||
tree: DisposalTreeItem[],
|
||||
occupancy: Awaited<ReturnType<typeof getDisposalOccupancy>>,
|
||||
borrows: Awaited<ReturnType<typeof loadDisposalAutoReturnBorrows>>
|
||||
) => {
|
||||
const [root, ...children] = tree
|
||||
if (!isDisposalAutoReturnRoot(root) || tree.some(item => occupancy.maintenance.has(item.id) || occupancy.disposal.has(item.id))) {
|
||||
return undefined
|
||||
}
|
||||
const records = borrows.get(root.id)
|
||||
if (records?.length !== 1 || records[0].return_time !== null || children.some(item =>
|
||||
item.mount_status !== 'mounted' || item.status !== '已借出' || item.total_quantity <= 0 ||
|
||||
item.remaining_quantity !== 0 || borrows.has(item.id)
|
||||
)) return undefined
|
||||
|
||||
const record = records[0]
|
||||
if (children.length && !record.children_snapshot) return undefined
|
||||
try {
|
||||
if (getReturnChildrenDiff(tree, record)) return undefined
|
||||
} catch (error) {
|
||||
if ((error as { status?: number }).status === 409) return undefined
|
||||
throw error
|
||||
}
|
||||
return { record, token: buildReturnConfirmationToken(tree, record) }
|
||||
}
|
||||
|
||||
export const getDisposalBlockedReason = (tree: DisposalTreeItem[], occupancy?: Awaited<ReturnType<typeof getDisposalOccupancy>>) => {
|
||||
const root = tree[0]
|
||||
if (root.parent_id !== null && root.status !== '已报废') return '挂载中的子资产不能单独申请报废,请先卸载'
|
||||
|
||||
@ -127,6 +127,7 @@ export interface BatchDisposalCandidate {
|
||||
status: string
|
||||
items: Array<{ id: number; equipment_code: string; equipment_name: string; total_quantity?: number }>
|
||||
blocked_reason: string | null
|
||||
auto_return_token?: string
|
||||
}
|
||||
|
||||
export interface BatchDisposalPreview {
|
||||
@ -135,7 +136,12 @@ export interface BatchDisposalPreview {
|
||||
}
|
||||
|
||||
export interface CreateBatchDisposalParams {
|
||||
assets: Array<{ equipment_id: number; item_ids: number[]; confirmed_quantities?: ConfirmedDisposalQuantity[] }>
|
||||
assets: Array<{
|
||||
equipment_id: number
|
||||
item_ids: number[]
|
||||
confirmed_quantities?: ConfirmedDisposalQuantity[]
|
||||
auto_return_token?: string
|
||||
}>
|
||||
disposal_reason: string
|
||||
disposal_method: string
|
||||
notes?: string
|
||||
|
||||
@ -60,6 +60,16 @@
|
||||
|
||||
<div v-if="preview" class="disposal-review" :class="{ 'disposal-review--with-fields': eligibleCandidates.length }">
|
||||
<section ref="previewSection" class="flex min-w-0 flex-col gap-3" aria-label="资产清单" tabindex="-1">
|
||||
<label v-if="autoReturnCandidates.length" class="flex min-h-11 cursor-pointer items-center gap-2 text-sm text-text-primary">
|
||||
<input
|
||||
type="checkbox"
|
||||
:checked="autoReturnEnabled"
|
||||
:disabled="busy"
|
||||
class="shrink-0 rounded border-border-hover bg-bg-elevated text-accent-primary accent-accent-primary focus:ring-accent-primary focus:ring-offset-bg-secondary"
|
||||
@change="changeAutoReturn"
|
||||
>
|
||||
自动归还所选在借资产
|
||||
</label>
|
||||
<div v-if="blockedCandidates.length || showBulkActions" class="disposal-preview-tools">
|
||||
<div v-if="blockedCandidates.length && eligibleCandidates.length" class="segmented-toggle disposal-scope" role="group" aria-label="资产状态">
|
||||
<button
|
||||
@ -84,7 +94,7 @@
|
||||
<p v-else-if="blockedCandidates.length" class="text-sm text-text-secondary">不可申请 {{ blockedCandidates.length }} 项</p>
|
||||
<div v-if="showBulkActions" class="ml-auto flex flex-wrap gap-1">
|
||||
<button
|
||||
v-if="hasStandaloneAssets"
|
||||
v-if="standaloneCandidates.length"
|
||||
type="button"
|
||||
class="btn-secondary disposal-quiet-button"
|
||||
:disabled="busy"
|
||||
@ -118,14 +128,13 @@
|
||||
type="checkbox"
|
||||
:value="candidate.equipment_id"
|
||||
:disabled="busy"
|
||||
:aria-label="candidate.items.length > 1
|
||||
? '确认整组申请 ' + candidate.equipment_code + ' 及其配件'
|
||||
: '申请资产 ' + candidate.equipment_code"
|
||||
:aria-label="candidateSelectionLabel(candidate)"
|
||||
class="shrink-0 rounded border-border-hover bg-bg-elevated text-accent-primary accent-accent-primary focus:ring-accent-primary focus:ring-offset-bg-secondary"
|
||||
>
|
||||
<span class="disposal-asset-identity">
|
||||
<span class="disposal-asset-name">{{ candidate.equipment_name || candidate.equipment_code }}</span>
|
||||
<span v-if="candidate.equipment_name" class="disposal-asset-code">{{ candidate.equipment_code }}</span>
|
||||
<span v-if="autoReturnEnabled && candidate.auto_return_token" class="text-xs text-status-warning">归还后申请</span>
|
||||
</span>
|
||||
</label>
|
||||
<span class="text-right text-xs tabular-nums text-text-secondary">
|
||||
@ -265,6 +274,7 @@ const errorMessage = ref('')
|
||||
const readingFile = ref(false)
|
||||
const loading = ref(false)
|
||||
const submitting = ref(false)
|
||||
const autoReturnEnabled = ref(false)
|
||||
const selectedIds = ref<number[]>([])
|
||||
const expandedCodes = ref(new Set<string>())
|
||||
const previewScope = ref<'eligible' | 'blocked'>('eligible')
|
||||
@ -275,7 +285,15 @@ const method = ref('报废')
|
||||
const notes = ref('')
|
||||
|
||||
const canApply = (candidate: BatchDisposalCandidate): candidate is BatchDisposalCandidate & { equipment_id: number } =>
|
||||
candidate.equipment_id !== null && candidate.items.length > 0 && !candidate.blocked_reason
|
||||
candidate.equipment_id !== null && candidate.items.length > 0 &&
|
||||
(candidate.auto_return_token ? autoReturnEnabled.value : !candidate.blocked_reason)
|
||||
|
||||
const candidateSelectionLabel = (candidate: BatchDisposalCandidate) => {
|
||||
const prefix = candidate.auto_return_token ? '归还后' : ''
|
||||
return candidate.items.length > 1
|
||||
? `${prefix}确认整组申请 ${candidate.equipment_code} 及其配件`
|
||||
: `${prefix}申请资产 ${candidate.equipment_code}`
|
||||
}
|
||||
|
||||
const blockedReason = (candidate: BatchDisposalCandidate) => {
|
||||
const message = candidate.blocked_reason || '不可申请'
|
||||
@ -284,9 +302,14 @@ const blockedReason = (candidate: BatchDisposalCandidate) => {
|
||||
}
|
||||
|
||||
const busy = computed(() => readingFile.value || loading.value || submitting.value)
|
||||
const autoReturnCandidates = computed(() => (preview.value?.candidates || []).filter((candidate) =>
|
||||
candidate.equipment_id !== null && candidate.items.length > 0 && Boolean(candidate.auto_return_token)
|
||||
))
|
||||
const eligibleCandidates = computed(() => (preview.value?.candidates || []).filter(canApply))
|
||||
const blockedCandidates = computed(() => (preview.value?.candidates || []).filter((candidate) => !canApply(candidate)))
|
||||
const hasStandaloneAssets = computed(() => eligibleCandidates.value.some((candidate) => candidate.items.length === 1))
|
||||
const standaloneCandidates = computed(() => eligibleCandidates.value.filter((candidate) =>
|
||||
candidate.items.length === 1 && !candidate.auto_return_token
|
||||
))
|
||||
const showBulkActions = computed(() => previewScope.value === 'eligible' && eligibleCandidates.value.length > previewPageSize)
|
||||
const visibleCandidates = computed(() => previewScope.value === 'eligible' ? eligibleCandidates.value : blockedCandidates.value)
|
||||
const previewPageCount = computed(() => Math.max(1, Math.ceil(visibleCandidates.value.length / previewPageSize)))
|
||||
@ -314,6 +337,17 @@ const changePreviewScope = (scope: 'eligible' | 'blocked') => {
|
||||
previewPage.value = 1
|
||||
}
|
||||
|
||||
const changeAutoReturn = (event: Event) => {
|
||||
if (busy.value) return
|
||||
autoReturnEnabled.value = (event.currentTarget as HTMLInputElement).checked
|
||||
if (!autoReturnEnabled.value) {
|
||||
const autoReturnIds = new Set(autoReturnCandidates.value.map((candidate) => candidate.equipment_id))
|
||||
selectedIds.value = selectedIds.value.filter((id) => !autoReturnIds.has(id))
|
||||
}
|
||||
previewScope.value = eligibleCandidates.value.length ? 'eligible' : 'blocked'
|
||||
previewPage.value = 1
|
||||
}
|
||||
|
||||
const changePreviewPage = (page: number) => {
|
||||
previewPage.value = page
|
||||
void nextTick(() => {
|
||||
@ -329,6 +363,7 @@ const toggleAccessories = (code: string) => {
|
||||
|
||||
const resetPreview = () => {
|
||||
preview.value = null
|
||||
autoReturnEnabled.value = false
|
||||
selectedIds.value = []
|
||||
expandedCodes.value.clear()
|
||||
previewPage.value = 1
|
||||
@ -338,13 +373,14 @@ const resetPreview = () => {
|
||||
const selectStandalone = () => {
|
||||
selectedIds.value = Array.from(new Set([
|
||||
...selectedIds.value,
|
||||
...eligibleCandidates.value.filter((candidate) => candidate.items.length === 1).map((candidate) => candidate.equipment_id)
|
||||
...standaloneCandidates.value.map((candidate) => candidate.equipment_id)
|
||||
]))
|
||||
}
|
||||
|
||||
const close = () => {
|
||||
if (submitting.value) return
|
||||
dialogElement.value?.close()
|
||||
resetPreview()
|
||||
emit('close')
|
||||
}
|
||||
|
||||
@ -420,7 +456,8 @@ const submit = async () => {
|
||||
return {
|
||||
equipment_id: candidate.equipment_id,
|
||||
item_ids: candidate.items.map((item) => item.id),
|
||||
confirmed_quantities: quantities.length === candidate.items.length ? quantities : undefined
|
||||
confirmed_quantities: quantities.length === candidate.items.length ? quantities : undefined,
|
||||
...(autoReturnEnabled.value && candidate.auto_return_token ? { auto_return_token: candidate.auto_return_token } : {})
|
||||
}
|
||||
})
|
||||
submitting.value = true
|
||||
@ -434,6 +471,7 @@ const submit = async () => {
|
||||
})
|
||||
if (!response.data) throw new Error('未收到审批结果,请核对报废记录')
|
||||
dialogElement.value?.close()
|
||||
resetPreview()
|
||||
emit('submitted', { count: response.data.count, equipmentIds: assets.flatMap((asset) => asset.item_ids) })
|
||||
} catch (error) {
|
||||
errorMessage.value = error instanceof Error ? error.message : '提交失败,请重试'
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user