feat: start asset disposal from the workflow page
This commit is contained in:
parent
961ce04d77
commit
9d1f065927
@ -0,0 +1,290 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import test from 'node:test'
|
||||
import type { Equipment, User } from '@prisma/client'
|
||||
import type { Request, Response } from 'express'
|
||||
|
||||
test('资产数量、报废和盘点的本机 MySQL 回归', {
|
||||
skip: process.env.RUN_BUSINESS_DB_TESTS !== 'true'
|
||||
}, async t => {
|
||||
const url = new URL(process.env.DATABASE_URL || '')
|
||||
assert.ok(url.protocol === 'mysql:' && ['127.0.0.1', 'localhost'].includes(url.hostname)
|
||||
&& url.port === '13309' && url.pathname === '/equipment_audit' && !url.search && !url.hash)
|
||||
|
||||
const prisma = (await import('../../utils/prisma')).default
|
||||
const { borrowEquipment, returnEquipment } = await import('../borrowController')
|
||||
const { updateEquipment } = await import('../equipmentController')
|
||||
const { createDisposal, getDisposalDetail, approveDisposal, completeDisposal } = await import('../disposalController')
|
||||
const { assignInventoryTaskUnassignedController, submitAdminInventoryScanController } = await import('../inventoryController')
|
||||
const { getPublicInventoryMeController, getPublicInventoryItemsController, submitPublicInventoryScanController,
|
||||
submitPublicInventoryExceptionController } = await import('../publicInventoryController')
|
||||
const prefix = `integrity-${randomUUID().slice(0, 12)}`
|
||||
const ids = { equipment: [] as number[], task: [] as number[], person: [] as number[],
|
||||
department: [] as number[], storage: [] as number[], user: [] as number[] }
|
||||
const previousNotificationFlag = process.env.YYD_NOTIFICATION_SEND_ENABLED
|
||||
process.env.YYD_NOTIFICATION_SEND_ENABLED = 'false'
|
||||
let storageId: number
|
||||
|
||||
const call = async (handler: (req: Request, res: Response) => unknown, user: User,
|
||||
body: unknown = {}, params: Record<string, string> = {}, session?: object, query?: Record<string, string>) => {
|
||||
const state = { status: 200, body: null as any }
|
||||
const response = { locals: { user: { id: user.id, username: user.username, name: user.name, role: user.role } },
|
||||
status(code: number) { state.status = code; return this },
|
||||
json(payload: unknown) { state.body = payload; return this } }
|
||||
await handler({ body, params, session, query, ip: '127.0.0.1' } as unknown as Request, response as unknown as Response)
|
||||
return state
|
||||
}
|
||||
|
||||
const asset = async (suffix: string, total = 1, parentId: number | null = null) => {
|
||||
const row = await prisma.equipment.create({ data: {
|
||||
equipment_code: `${prefix}-${suffix}`, equipment_name: `${prefix}-${suffix}`, equipment_type: '测试',
|
||||
total_quantity: total, remaining_quantity: total, unit_price: 100, total_value: total * 100,
|
||||
available_value: total * 100, status: '可用', storage_location_id: storageId,
|
||||
parent_id: parentId, mount_status: parentId ? 'mounted' : 'none'
|
||||
} })
|
||||
ids.equipment.push(row.id)
|
||||
return row
|
||||
}
|
||||
|
||||
try {
|
||||
const users = await Promise.all(['it', 'administrative'].map(async role => {
|
||||
const user = await prisma.user.create({ data: { username: `${prefix}-${role}`, name: prefix,
|
||||
password: 'local-test-only', role } })
|
||||
ids.user.push(user.id)
|
||||
return user
|
||||
}))
|
||||
const [operator, reviewer] = users
|
||||
const departments = await Promise.all(['A', 'B'].map(async name => {
|
||||
const row = await prisma.department.create({ data: { name: `${prefix}-${name}`, source_system: 'ding_hr_business' } })
|
||||
ids.department.push(row.id)
|
||||
return row
|
||||
}))
|
||||
const people = await Promise.all([0, 0, 1].map(async (department, index) => {
|
||||
const row = await prisma.person.create({ data: { nickname: `${prefix}-${index}`,
|
||||
real_name: prefix, status: 'active', main_department_id: departments[department].id } })
|
||||
ids.person.push(row.id)
|
||||
return row
|
||||
}))
|
||||
storageId = (await prisma.storageLocation.create({ data: { name: prefix } })).id
|
||||
ids.storage.push(storageId)
|
||||
|
||||
const equipmentState = (row: Equipment) => prisma.equipment.findUniqueOrThrow({ where: { id: row.id } })
|
||||
const edit = (row: Equipment, total_quantity: number, description?: string) =>
|
||||
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 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) })
|
||||
const details = (id: number) => call(getDisposalDetail, reviewer, {}, { id: String(id) })
|
||||
const legacySnapshot = (disposalId: number) => prisma.disposalItem.updateMany({
|
||||
where: { disposal_id: disposalId }, data: { snapshot_json: '{"status":"可用"}' }
|
||||
})
|
||||
|
||||
await t.test('同部门可共借,数量不得少于实际未还量,历史跨部门仍可逐笔归还', async () => {
|
||||
const row = await asset('stock', 2)
|
||||
const first = await borrow(row, people[0].id)
|
||||
assert.equal(first.status, 200, JSON.stringify(first.body))
|
||||
const otherDepartment = await borrow(row, people[2].id)
|
||||
assert.equal(otherDepartment.status, 409, JSON.stringify(otherDepartment.body))
|
||||
assert.equal((await equipmentState(row)).department_id, departments[0].id)
|
||||
const second = await borrow(row, people[1].id)
|
||||
assert.equal(second.status, 200, JSON.stringify(second.body))
|
||||
assert.equal((await edit(row, 1)).status, 409)
|
||||
const stillBorrowed = await equipmentState(row)
|
||||
assert.deepEqual([stillBorrowed.total_quantity, stillBorrowed.remaining_quantity, stillBorrowed.status], [2, 0, '已借出'])
|
||||
assert.equal(await prisma.borrowRecord.count({ where: { equipment_id: row.id, status: '已借出' } }), 2)
|
||||
assert.equal((await edit(row, 3)).status, 200)
|
||||
const corrected = await equipmentState(row)
|
||||
assert.deepEqual([corrected.total_quantity, corrected.remaining_quantity, corrected.department_id, corrected.storage_location_id],
|
||||
[3, 1, departments[0].id, storageId])
|
||||
|
||||
// A current holder can change departments independently of existing loan records.
|
||||
await prisma.person.update({ where: { id: people[1].id }, data: { main_department_id: departments[1].id } })
|
||||
assert.equal((await borrow(row, people[0].id)).status, 409)
|
||||
for (const borrowRecordId of [second.body.data.id, first.body.data.id]) {
|
||||
const returned = await call(returnEquipment, operator, { equipment_id: row.id, borrow_record_id: borrowRecordId })
|
||||
assert.equal(returned.status, 200, JSON.stringify(returned.body))
|
||||
assert.equal(returned.body.data.need_confirm, undefined)
|
||||
}
|
||||
const available = await equipmentState(row)
|
||||
assert.deepEqual([available.remaining_quantity, available.status, available.storage_location_id], [3, '可用', storageId])
|
||||
})
|
||||
|
||||
await t.test('整机借出时改主资产数量不会释放挂载件,配件也不能独立改数量', async () => {
|
||||
const root = await asset('root-stock')
|
||||
const child = await asset('child-stock', 1, root.id)
|
||||
assert.equal((await borrow(root, people[0].id)).status, 200)
|
||||
assert.equal((await edit(child, 2)).status, 409)
|
||||
assert.equal((await edit(root, 2)).status, 200)
|
||||
const checked = await equipmentState(child)
|
||||
assert.deepEqual([checked.parent_id, checked.status, checked.total_quantity, checked.remaining_quantity, checked.storage_location_id],
|
||||
[root.id, '已借出', 1, 0, storageId])
|
||||
})
|
||||
|
||||
await t.test('审批冻结整棵树的数量,数量纠错和完成均检查冻结值', async () => {
|
||||
const root = await asset('disposal-root', 2)
|
||||
const child = await asset('disposal-child', 1, root.id)
|
||||
const created = await submit(root, [root.id, child.id])
|
||||
assert.equal(created.status, 200, JSON.stringify(created.body))
|
||||
const id = created.body.data.id
|
||||
const pending = await details(id)
|
||||
assert.deepEqual(pending.body.data.items.map((item: any) =>
|
||||
[item.equipment.total_quantity, JSON.parse(item.snapshot_json).total_quantity]), [[2, 2], [1, 1]])
|
||||
assert.equal((await edit(root, 3)).status, 409)
|
||||
assert.equal((await edit(root, 2, '数量原样提交')).status, 200)
|
||||
assert.equal((await equipmentState(root)).description, '数量原样提交')
|
||||
assert.equal((await approve(id)).status, 200)
|
||||
assert.equal((await edit(child, 2)).status, 409)
|
||||
// Represent a mismatch already present in historical data.
|
||||
await prisma.equipment.update({ where: { id: child.id }, data: { total_quantity: 2, remaining_quantity: 2 } })
|
||||
const mismatch = await complete(id)
|
||||
assert.equal(mismatch.status, 409, JSON.stringify(mismatch.body))
|
||||
assert.match(mismatch.body.message, /数量/)
|
||||
assert.equal((await equipmentState(root)).status, '待报废')
|
||||
await prisma.equipment.update({ where: { id: child.id }, data: { total_quantity: 1, remaining_quantity: 1 } })
|
||||
assert.equal((await complete(id)).status, 200)
|
||||
assert.deepEqual([(await equipmentState(root)).status, (await equipmentState(child)).status], ['已报废', '已报废'])
|
||||
})
|
||||
|
||||
await t.test('历史单须由审批人逐件确认数量并保留原审批,缺配件范围的旧单不能完成', async () => {
|
||||
const confirmer = await prisma.user.create({ data: { username: `${prefix}-confirm`, name: prefix,
|
||||
password: 'local-test-only', role: 'administrative' } })
|
||||
ids.user.push(confirmer.id)
|
||||
for (const suffix of ['old-pending', 'old-approved', 'old-subset']) {
|
||||
const row = await asset(suffix, 2)
|
||||
const created = await submit(row)
|
||||
assert.equal(created.status, 200, JSON.stringify(created.body))
|
||||
const id = created.body.data.id
|
||||
if (suffix === 'old-pending') {
|
||||
await legacySnapshot(id)
|
||||
const pending = await details(id)
|
||||
assert.equal(pending.body.data.requires_quantity_confirmation, true)
|
||||
assert.equal(pending.body.data.items[0].equipment.total_quantity, 2)
|
||||
assert.equal((await approve(id)).status, 409)
|
||||
assert.equal((await approve(id, { confirmed_quantities: [{ equipment_id: row.id, total_quantity: 1 }] })).status, 409)
|
||||
assert.equal((await approve(id, { confirmed_quantities: [{ equipment_id: row.id, total_quantity: 2 }] })).status, 200)
|
||||
const approved = await details(id)
|
||||
assert.equal(approved.body.data.requires_quantity_confirmation, false)
|
||||
assert.equal(JSON.parse(approved.body.data.items[0].snapshot_json).total_quantity, 2)
|
||||
continue
|
||||
}
|
||||
assert.equal((await approve(id)).status, 200)
|
||||
await legacySnapshot(id)
|
||||
if (suffix === 'old-subset') await asset('old-unrecorded-child', 1, row.id)
|
||||
const result = await complete(id)
|
||||
assert.equal(result.status, 409, JSON.stringify(result.body))
|
||||
assert.equal((await equipmentState(row)).status, '待报废')
|
||||
const original = await prisma.disposalRecord.findUniqueOrThrow({ where: { id } })
|
||||
const reconfirm = (total_quantity: number) => approve(id, {
|
||||
reconfirm_quantities: true, confirmed_quantities: [{ equipment_id: row.id, total_quantity }]
|
||||
}, confirmer)
|
||||
assert.equal((await reconfirm(1)).status, 409)
|
||||
assert.equal((await reconfirm(2)).status, suffix === 'old-approved' ? 200 : 409)
|
||||
if (suffix === 'old-approved') {
|
||||
assert.equal((await reconfirm(2)).status, 409)
|
||||
const confirmed = (await details(id)).body.data
|
||||
assert.equal(confirmed.requires_quantity_confirmation, false)
|
||||
assert.deepEqual([confirmed.status, confirmed.approved_by, confirmed.approved_at], ['approved', reviewer.id, original.approved_at])
|
||||
assert.deepEqual(confirmed.actions.filter((action: any) => action.action_type === 'quantity_confirmed')
|
||||
.map((action: any) => [action.operator_id, JSON.parse(action.detail)]),
|
||||
[[confirmer.id, [{ equipment_id: row.id, total_quantity: 2 }]]])
|
||||
assert.equal((await complete(id)).status, 200)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
await t.test('拒绝已核验项重新分配和双标签串单,扫码事务遇到关单保留会话', async () => {
|
||||
const task = await prisma.inventoryTask.create({ data: { title: prefix, public_token: prefix, created_by: operator.id,
|
||||
identity_mode: 'legacy', items_count: 2, unassigned_count: 1, participants_count: 1 } })
|
||||
ids.task.push(task.id)
|
||||
const participant = await prisma.inventoryTaskParticipant.create({ data: { task_id: task.id, person_id: people[0].id,
|
||||
person_name: people[0].real_name, person_nickname: people[0].nickname } })
|
||||
const item = async (suffix: string, participantId: number | null) => {
|
||||
const row = await asset(suffix)
|
||||
return prisma.inventoryTaskItem.create({ data: { task_id: task.id, equipment_id: row.id,
|
||||
equipment_code: row.equipment_code, equipment_name: row.equipment_name, equipment_type: row.equipment_type,
|
||||
is_unassigned: !participantId, participant_id: participantId } })
|
||||
}
|
||||
const unassigned = await item('inventory-unassigned', null)
|
||||
const assigned = await item('inventory-assigned', participant.id)
|
||||
const params = { id: String(task.id), itemId: String(unassigned.id) }
|
||||
assert.equal((await call(submitAdminInventoryScanController, operator, { equipment_code: unassigned.equipment_code }, params)).status, 200)
|
||||
const stale = await call(assignInventoryTaskUnassignedController, operator, { person_id: people[1].id }, params)
|
||||
assert.equal(stale.status, 409, JSON.stringify(stale.body))
|
||||
const stored = await prisma.inventoryTaskItem.findUniqueOrThrow({ where: { id: unassigned.id } })
|
||||
assert.deepEqual([stored.check_status, stored.participant_id], ['checked', null])
|
||||
assert.equal(await prisma.inventoryTaskParticipant.count({ where: { task_id: task.id } }), 1)
|
||||
|
||||
const otherTask = await prisma.inventoryTask.create({ data: { title: prefix, public_token: `${prefix}-other`,
|
||||
created_by: operator.id, identity_mode: 'legacy', items_count: 1, participants_count: 1 } })
|
||||
ids.task.push(otherTask.id)
|
||||
const otherParticipant = await prisma.inventoryTaskParticipant.create({ data: { task_id: otherTask.id, person_id: people[0].id,
|
||||
person_name: people[0].real_name, person_nickname: people[0].nickname } })
|
||||
const otherItem = await prisma.inventoryTaskItem.create({ data: {
|
||||
task_id: otherTask.id, participant_id: otherParticipant.id, equipment_id: assigned.equipment_id,
|
||||
equipment_code: assigned.equipment_code, equipment_name: assigned.equipment_name, equipment_type: assigned.equipment_type
|
||||
} })
|
||||
const session = { inventoryParticipant: { taskId: otherTask.id, participantId: otherParticipant.id, publicToken: otherTask.public_token } }
|
||||
const scanBody = { task_token: task.public_token, participant_id: participant.id, equipment_code: assigned.equipment_code }
|
||||
const query = { task_token: task.public_token }
|
||||
assert.equal((await call(getPublicInventoryMeController, operator, {}, {}, session, query)).status, 409)
|
||||
assert.equal((await call(getPublicInventoryItemsController, operator, {}, {}, session, query)).status, 409)
|
||||
assert.equal((await call(submitPublicInventoryScanController, operator, scanBody, {}, session)).status, 409)
|
||||
assert.equal((await call(submitPublicInventoryExceptionController, operator, { ...scanBody, exception_type: '其他' },
|
||||
{ itemId: String(otherItem.id) }, session)).status, 409)
|
||||
const otherQuery = { task_token: otherTask.public_token, participant_id: String(participant.id) }
|
||||
assert.equal((await call(getPublicInventoryItemsController, operator, {}, {}, session, otherQuery)).status, 409)
|
||||
const otherScan = { ...scanBody, task_token: otherTask.public_token }
|
||||
assert.equal((await call(submitPublicInventoryScanController, operator, otherScan, {}, session)).status, 409)
|
||||
assert.equal((await call(submitPublicInventoryScanController, operator,
|
||||
{ equipment_code: assigned.equipment_code }, {}, session)).status, 422)
|
||||
assert.equal(await prisma.inventoryTaskAction.count({ where: { task_id: otherTask.id } }), 0)
|
||||
assert.equal((await call(submitPublicInventoryScanController, operator,
|
||||
{ ...otherScan, participant_id: otherParticipant.id }, {}, session)).status, 200)
|
||||
assert.equal((await prisma.inventoryTaskItem.findUniqueOrThrow({ where: { id: otherItem.id } })).check_status, 'checked')
|
||||
|
||||
session.inventoryParticipant = { taskId: task.id, participantId: participant.id, publicToken: prefix }
|
||||
const context = { ...session.inventoryParticipant }
|
||||
const transaction = prisma.$transaction
|
||||
prisma.$transaction = (async (...args: any[]) => {
|
||||
await prisma.inventoryTask.update({ where: { id: task.id }, data: { status: 'closed' } })
|
||||
return Reflect.apply(transaction, prisma, args)
|
||||
}) as typeof transaction
|
||||
try {
|
||||
const scan = await call(submitPublicInventoryScanController, operator, scanBody, {}, session)
|
||||
assert.equal(scan.status, 403, JSON.stringify(scan.body))
|
||||
assert.match(scan.body.message, /关闭/)
|
||||
assert.deepEqual(session.inventoryParticipant, context)
|
||||
} finally {
|
||||
prisma.$transaction = transaction
|
||||
}
|
||||
assert.equal((await prisma.inventoryTaskItem.findUniqueOrThrow({ where: { id: assigned.id } })).check_status, 'pending')
|
||||
})
|
||||
} finally {
|
||||
if (previousNotificationFlag === undefined) delete process.env.YYD_NOTIFICATION_SEND_ENABLED
|
||||
else process.env.YYD_NOTIFICATION_SEND_ENABLED = previousNotificationFlag
|
||||
try {
|
||||
await prisma.$transaction(async tx => {
|
||||
const equipmentId = { in: ids.equipment }
|
||||
await tx.notification.deleteMany({ where: { type: 'disposal', title: { contains: prefix } } })
|
||||
await tx.inventoryTask.deleteMany({ where: { id: { in: ids.task } } })
|
||||
await tx.operationLog.deleteMany({ where: { user_id: { in: ids.user } } })
|
||||
await tx.disposalRecord.deleteMany({ where: { equipment_id: equipmentId } })
|
||||
await tx.borrowRecord.deleteMany({ where: { equipment_id: equipmentId } })
|
||||
await tx.assetTransferRecord.deleteMany({ where: { root_equipment_id: equipmentId } })
|
||||
await tx.equipment.updateMany({ where: { id: equipmentId }, data: { parent_id: null } })
|
||||
await tx.equipment.deleteMany({ where: { id: equipmentId } })
|
||||
await tx.user.deleteMany({ where: { id: { in: ids.user } } })
|
||||
await tx.person.deleteMany({ where: { id: { in: ids.person } } })
|
||||
await tx.department.deleteMany({ where: { id: { in: ids.department } } })
|
||||
await tx.storageLocation.deleteMany({ where: { id: { in: ids.storage } } })
|
||||
}, { timeout: 10000 })
|
||||
} finally {
|
||||
await prisma.$disconnect()
|
||||
}
|
||||
}
|
||||
})
|
||||
@ -37,7 +37,8 @@ test('批量报废在本机隔离 MySQL 验证完整资产树、事务和审批
|
||||
await handler({ body, ip } as any, response as any)
|
||||
return state
|
||||
}
|
||||
const submit = (assets: { equipment_id: number; item_ids: number[] }[], ip?: string) => call(createBatchDisposal,
|
||||
const submit = (assets: { equipment_id: number; item_ids: number[];
|
||||
confirmed_quantities?: { equipment_id: number; total_quantity: number }[] }[], ip?: string) => call(createBatchDisposal,
|
||||
{ assets, disposal_reason: '设备老化', disposal_method: '报废', notes: '本机验证' }, ip)
|
||||
|
||||
const codes = Array.from({ length: 335 }, (_, index) => data(`list-${String(index).padStart(3, '0')}`))
|
||||
@ -68,6 +69,7 @@ test('批量报废在本机隔离 MySQL 验证完整资产树、事务和审批
|
||||
assert.deepEqual(response.body.data.candidates.map((row: { equipment_code: string }) => row.equipment_code), distinctCodes)
|
||||
assert.deepEqual(response.body.data.duplicate_codes, distinctCodes.slice(0, 166))
|
||||
assert.deepEqual(response.body.data.candidates[0].items.map((row: { id: number }) => row.id), [root.id, child.id, nested.id])
|
||||
assert.deepEqual(response.body.data.candidates[0].items.map((row: { total_quantity: number }) => row.total_quantity), [1, 1, 1])
|
||||
assert.ok(response.body.data.candidates.every((row: { blocked_reason: string | null }) => row.blocked_reason === null))
|
||||
const mixed = await call(previewBatchDisposal, {
|
||||
equipment_ids: [root.id], equipment_codes: [root.equipment_code.toUpperCase(), child.equipment_code, 'missing-code',
|
||||
@ -98,6 +100,11 @@ test('批量报废在本机隔离 MySQL 验证完整资产树、事务和审批
|
||||
assert.equal(stale.status, 409); assert.match(stale.body.message, new RegExp(nested.equipment_code))
|
||||
const overlap = await submit([{ equipment_id: root.id, item_ids: [root.id, child.id, nested.id] }, { equipment_id: child.id, item_ids: [child.id] }])
|
||||
assert.equal(overlap.status, 422)
|
||||
const quantityMismatch = await submit([{ equipment_id: independent.id, item_ids: [independent.id] },
|
||||
{ equipment_id: root.id, item_ids: [root.id, child.id, nested.id],
|
||||
confirmed_quantities: [root, child, nested].map(row => ({ equipment_id: row.id, total_quantity: row.id === child.id ? 2 : 1 })) }])
|
||||
assert.equal(quantityMismatch.status, 409)
|
||||
assert.match(quantityMismatch.body.message, /数量/)
|
||||
const occupied = await submit([{ equipment_id: independent.id, item_ids: [independent.id] }, { equipment_id: loaned.id, item_ids: [loaned.id] }])
|
||||
assert.equal(occupied.status, 409); assert.match(occupied.body.message, /未归还/)
|
||||
const ids = [independent.id, root.id, child.id, nested.id]
|
||||
|
||||
@ -282,11 +282,13 @@ test('并发审批 CAS 失败时返回 409,不追加动作也不改资产', as
|
||||
equipment_code: rootEquipment.equipment_code,
|
||||
parent_equipment_id: null,
|
||||
pre_status: '可用',
|
||||
snapshot_json: JSON.stringify({ total_quantity: 1, remaining_quantity: 1 }),
|
||||
equipment: { ...rootEquipment, status: '待报废' }
|
||||
}]
|
||||
}
|
||||
|
||||
;(prisma.$transaction as any) = async (callback: any) => callback({
|
||||
$queryRaw: async () => [],
|
||||
disposalRecord: {
|
||||
findUnique: async () => disposal,
|
||||
updateMany: async () => ({ count: 0 })
|
||||
@ -297,6 +299,7 @@ test('并发审批 CAS 失败时返回 409,不追加动作也不改资产', as
|
||||
}
|
||||
},
|
||||
equipment: {
|
||||
findMany: async () => [],
|
||||
updateMany: async () => {
|
||||
equipmentWriteCount += 1
|
||||
return { count: 1 }
|
||||
@ -326,6 +329,8 @@ test('行政可以审批自己发起的报废申请', async () => {
|
||||
let actionData: Record<string, any> | undefined
|
||||
|
||||
;(prisma.$transaction as any) = async (callback: any) => callback({
|
||||
$queryRaw: async () => [],
|
||||
equipment: { findMany: async () => [] },
|
||||
disposalRecord: {
|
||||
findUnique: async () => ({
|
||||
id: 94,
|
||||
@ -333,7 +338,9 @@ test('行政可以审批自己发起的报废申请', async () => {
|
||||
equipment_code: rootEquipment.equipment_code,
|
||||
applied_by: 6,
|
||||
status: 'pending',
|
||||
items: []
|
||||
items: [{ equipment_id: rootEquipment.id, parent_equipment_id: null,
|
||||
snapshot_json: JSON.stringify({ total_quantity: 1, remaining_quantity: 1 }),
|
||||
equipment: { ...rootEquipment, status: '待报废' } }]
|
||||
}),
|
||||
updateMany: async (args: any) => {
|
||||
updatedData = args.data
|
||||
@ -398,11 +405,13 @@ test('驳回报废时按每个 item.pre_status 分别恢复', async () => {
|
||||
}
|
||||
|
||||
;(prisma.$transaction as any) = async (callback: any) => callback({
|
||||
$queryRaw: async () => [],
|
||||
disposalRecord: {
|
||||
findUnique: async () => disposal,
|
||||
updateMany: async () => ({ count: 1 })
|
||||
},
|
||||
equipment: {
|
||||
findMany: async ({ where }: any) => where.parent_id.in.includes(rootEquipment.id) ? [disposal.items[1].equipment] : [],
|
||||
updateMany: async (args: any) => {
|
||||
restoredStatuses.push(args.data.status)
|
||||
return { count: 1 }
|
||||
@ -537,7 +546,8 @@ test('IT不能通过详情接口查看他人申请,行政可以查看全部流
|
||||
applied_by: 99,
|
||||
status: 'completed',
|
||||
notes: '历史备注',
|
||||
completion_notes: null
|
||||
completion_notes: null,
|
||||
items: []
|
||||
})
|
||||
|
||||
try {
|
||||
|
||||
@ -41,7 +41,7 @@ test('disposal history limits IT to applicant across root and child equipment re
|
||||
test('disposal detail permits IT own record and rejects another applicant', async () => {
|
||||
const original = prisma.disposalRecord.findUnique
|
||||
;(prisma.disposalRecord.findUnique as any) = async (args: any) => ({
|
||||
id: args.where.id, applied_by: args.where.id === 1 ? 6 : 99, status: 'pending'
|
||||
id: args.where.id, applied_by: args.where.id === 1 ? 6 : 99, status: 'pending', items: []
|
||||
})
|
||||
try {
|
||||
for (const [role, id, code] of [['it', '1', 200], ['it', '2', 403], ['admin', '2', 200], ['administrative', '2', 200]] as const) {
|
||||
|
||||
@ -57,7 +57,7 @@ test('已丢失资产基础编辑保留状态与零库存,禁止增总数量
|
||||
let writes = 0
|
||||
;(prisma.equipment.findUnique as any) = async () => lostEquipment
|
||||
;(prisma.$transaction as any) = async (callback: any) => callback({
|
||||
$queryRawUnsafe: async () => [],
|
||||
$queryRaw: async () => [],
|
||||
operationLog: { create: async () => ({ id: 1 }) },
|
||||
equipment: {
|
||||
updateMany: async (args: any) => { writes++; updateData = args.data; return { count: 1 } },
|
||||
@ -68,8 +68,8 @@ test('已丢失资产基础编辑保留状态与零库存,禁止增总数量
|
||||
const metadata = createMockResponse()
|
||||
await updateEquipment({ params: { id: '903' }, body: { equipment_name: '丢失主机', total_quantity: 1, unit_price: 120 } } as any, metadata.res as any)
|
||||
assert.equal(metadata.responseBody.statusCode, 200)
|
||||
assert.equal(updateData.status, '已丢失')
|
||||
assert.equal(updateData.remaining_quantity, 0)
|
||||
assert.equal(updateData.status, undefined)
|
||||
assert.equal(updateData.remaining_quantity, undefined)
|
||||
assert.equal(updateData.available_value, 0)
|
||||
assert.equal(updateData.borrowed_value, 0)
|
||||
const quantity = createMockResponse()
|
||||
@ -89,7 +89,7 @@ test('普通编辑资产时不应把待报废资产冲回可用', async () => {
|
||||
let capturedUpdateData: any = null
|
||||
;(prisma.equipment.findUnique as any) = async () => currentEquipment
|
||||
;(prisma.$transaction as any) = async (callback: any) => callback({
|
||||
$queryRawUnsafe: async () => [],
|
||||
$queryRaw: async () => [],
|
||||
operationLog: { create: async () => ({ id: 1 }) },
|
||||
equipment: {
|
||||
updateMany: async (args: any) => {
|
||||
@ -119,7 +119,8 @@ test('普通编辑资产时不应把待报废资产冲回可用', async () => {
|
||||
)
|
||||
|
||||
assert.equal(responseBody.statusCode, 200)
|
||||
assert.equal(capturedUpdateData.status, '待报废')
|
||||
assert.equal(capturedUpdateData.status, undefined)
|
||||
assert.equal(capturedUpdateData.total_quantity, undefined)
|
||||
} finally {
|
||||
;(prisma.equipment.findUnique as any) = originalFindUnique
|
||||
;(prisma.$transaction as any) = originalTransaction
|
||||
@ -160,7 +161,7 @@ test('资产状态在保存前变化时 CAS 失败并返回 409', async () => {
|
||||
return currentEquipment
|
||||
}
|
||||
;(prisma.$transaction as any) = async (callback: any) => callback({
|
||||
$queryRawUnsafe: async () => [],
|
||||
$queryRaw: async () => [],
|
||||
equipment: {
|
||||
updateMany: async (args: any) => {
|
||||
capturedWhere = args.where
|
||||
@ -210,7 +211,7 @@ test('行政纠错只写入本次提交的基础字段', async () => {
|
||||
;(prisma.disposalItem.count as any) = async () => 0
|
||||
;(prisma.department.findFirst as any) = async () => ({ id: 7, name: '行政部' })
|
||||
;(prisma.$transaction as any) = async (callback: any) => callback({
|
||||
$queryRawUnsafe: async () => [],
|
||||
$queryRaw: async () => [],
|
||||
operationLog: { create: async () => ({ id: 1 }) },
|
||||
borrowRecord: { count: async () => 0 },
|
||||
maintenanceRecord: { count: async () => 0 },
|
||||
@ -302,7 +303,7 @@ test('修改资产类型名称时同步更新 asset_type_id', async () => {
|
||||
;(prisma.equipment.count as any) = async () => 0
|
||||
;(prisma.assetType.findFirst as any) = async () => newType
|
||||
;(prisma.$transaction as any) = async (callback: any) => callback({
|
||||
$queryRawUnsafe: async () => [],
|
||||
$queryRaw: async () => [],
|
||||
operationLog: { create: async () => ({ id: 1 }) },
|
||||
assetType: { findUnique: async () => newType },
|
||||
equipment: {
|
||||
|
||||
@ -38,6 +38,8 @@ const disposalInclude = {
|
||||
equipment_type: true,
|
||||
status: true,
|
||||
parent_id: true,
|
||||
total_quantity: true,
|
||||
remaining_quantity: true,
|
||||
storage_location_id: true,
|
||||
department_id: true
|
||||
}
|
||||
@ -249,6 +251,15 @@ const withHistoricalDisposalNotes = <T extends {
|
||||
: null
|
||||
})
|
||||
|
||||
const readDisposalItemSnapshot = (snapshot: string | null): Record<string, unknown> | null => {
|
||||
try {
|
||||
const parsed = snapshot ? JSON.parse(snapshot) : {}
|
||||
return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
const readDisposalSubmission = (body: Record<string, unknown>) => {
|
||||
const reason = typeof body.disposal_reason === 'string' ? body.disposal_reason.trim() : ''
|
||||
const method = typeof body.disposal_method === 'string' ? body.disposal_method.trim() : ''
|
||||
@ -280,7 +291,8 @@ const writeDisposalSubmission = async (
|
||||
pre_status: item.status,
|
||||
snapshot_json: JSON.stringify({
|
||||
equipment_code: item.equipment_code, equipment_name: item.equipment_name, parent_id: item.parent_id,
|
||||
department_id: item.department_id, storage_location_id: item.storage_location_id, status: item.status
|
||||
department_id: item.department_id, storage_location_id: item.storage_location_id, status: item.status,
|
||||
total_quantity: item.total_quantity, remaining_quantity: item.remaining_quantity
|
||||
})
|
||||
})) },
|
||||
actions: { create: {
|
||||
@ -429,7 +441,7 @@ export const previewBatchDisposal = async (req: Request, res: Response) => {
|
||||
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 }) => ({ id, equipment_code, equipment_name })),
|
||||
items: tree.map(({ id, equipment_code, equipment_name, total_quantity }) => ({ id, equipment_code, equipment_name, total_quantity })),
|
||||
blocked_reason: root ? getDisposalBlockedReason(tree, occupancy) : '未找到资产'
|
||||
}
|
||||
})
|
||||
@ -449,7 +461,7 @@ export const createBatchDisposal = async (req: Request, res: Response) => {
|
||||
}
|
||||
const input = readDisposalSubmission(req.body)
|
||||
const rootIds: number[] = []
|
||||
const confirmed = new Map<number, number[]>()
|
||||
const confirmed = new Map<number, { itemIds: number[]; quantities?: Map<number, number> }>()
|
||||
const lockedIds = new Set<number>()
|
||||
for (const asset of assets) {
|
||||
if (!isEquipmentId(asset?.equipment_id) || !Array.isArray(asset.item_ids) ||
|
||||
@ -462,7 +474,11 @@ export const createBatchDisposal = async (req: Request, res: Response) => {
|
||||
lockedIds.add(id)
|
||||
}
|
||||
rootIds.push(asset.equipment_id)
|
||||
confirmed.set(asset.equipment_id, asset.item_ids)
|
||||
confirmed.set(asset.equipment_id, {
|
||||
itemIds: asset.item_ids,
|
||||
quantities: asset.confirmed_quantities === undefined
|
||||
? undefined : readConfirmedDisposalQuantities(asset.confirmed_quantities)
|
||||
})
|
||||
}
|
||||
|
||||
const disposalIds = await prisma.$transaction(async tx => {
|
||||
@ -476,7 +492,9 @@ export const createBatchDisposal = async (req: Request, res: Response) => {
|
||||
const tree = trees.get(id)!
|
||||
const blocked = getDisposalBlockedReason(tree)
|
||||
if (blocked) throw new DisposalConflictError(`${tree[0].equipment_code}:${blocked}`)
|
||||
assertDisposalItemsConfirmed(tree, confirmed.get(id)!)
|
||||
const confirmation = confirmed.get(id)!
|
||||
assertDisposalItemsConfirmed(tree, confirmation.itemIds)
|
||||
if (confirmation.quantities) assertConfirmedDisposalQuantities(tree, confirmation.quantities)
|
||||
}
|
||||
const occupancy = await getDisposalOccupancy(tx, [...lockedIds])
|
||||
for (const id of rootIds) {
|
||||
@ -645,16 +663,108 @@ export const getDisposalDetail = async (req: Request, res: Response) => {
|
||||
if (visibility.applied_by && disposal.applied_by !== visibility.applied_by) {
|
||||
return errorResponse(res, '无权查看该报废申请', 403)
|
||||
}
|
||||
successResponse(res, withHistoricalDisposalNotes(disposal), '获取成功')
|
||||
successResponse(res, {
|
||||
...withHistoricalDisposalNotes(disposal),
|
||||
requires_quantity_confirmation: disposal.items.some(item => {
|
||||
const snapshot = readDisposalItemSnapshot(item.snapshot_json)
|
||||
return snapshot !== null && snapshot.total_quantity === undefined
|
||||
})
|
||||
}, '获取成功')
|
||||
} catch (error: any) {
|
||||
errorResponse(res, error.message || '获取报废记录详情失败', error.status || 500)
|
||||
}
|
||||
}
|
||||
|
||||
const disposalDecisionInclude = { items: { include: { equipment: true } } } as const
|
||||
|
||||
const loadLockedDisposalDecision = async (tx: Prisma.TransactionClient, id: number, expectedStatus: string) => {
|
||||
const initial = await tx.disposalRecord.findUnique({ where: { id }, include: disposalDecisionInclude })
|
||||
if (!initial) throw Object.assign(new Error('报废记录不存在'), { status: 404 })
|
||||
const equipmentIds = new Set([initial.equipment_id, ...initial.items.map(item => item.equipment_id)])
|
||||
await lockEquipmentRows(tx, [...equipmentIds])
|
||||
const disposal = await tx.disposalRecord.findUnique({ where: { id }, include: disposalDecisionInclude })
|
||||
if (!disposal || disposal.status !== expectedStatus) throw new DisposalConflictError('该申请已被其他人处理,请刷新后查看')
|
||||
const root = disposal.items.find(item => item.equipment_id === disposal.equipment_id)?.equipment
|
||||
if (!root || root.parent_id !== null || !equipmentIds.has(root.id) || disposal.items.some(item => !equipmentIds.has(item.equipment_id))) {
|
||||
throw new DisposalConflictError('报废明细范围已变化或缺少主资产,请先核查')
|
||||
}
|
||||
const trees = await loadDisposalTrees(tx, [root])
|
||||
assertDisposalItemsConfirmed(trees.get(root.id)!, disposal.items.map(item => item.equipment_id))
|
||||
const changedItem = disposal.items.find(item => item.equipment.status !== '待报废' || item.equipment.parent_id !== item.parent_equipment_id)
|
||||
if (changedItem) throw new DisposalConflictError(`资产 ${changedItem.equipment_code} 的状态或挂载关系已变化,请先核查`)
|
||||
return disposal
|
||||
}
|
||||
|
||||
const verifyDisposalQuantities = async (
|
||||
tx: Prisma.TransactionClient,
|
||||
disposal: Awaited<ReturnType<typeof loadLockedDisposalDecision>>,
|
||||
confirmation?: Map<number, number>
|
||||
) => {
|
||||
if (confirmation) assertConfirmedDisposalQuantities(disposal.items.map(item => item.equipment), confirmation)
|
||||
let restoredSnapshot = false
|
||||
for (const item of disposal.items) {
|
||||
const { total_quantity, remaining_quantity } = item.equipment
|
||||
if (total_quantity < 1 || remaining_quantity !== total_quantity) {
|
||||
throw new DisposalConflictError(`资产 ${item.equipment_code} 的库存与报废数量不一致,请先核查`)
|
||||
}
|
||||
const snapshot = readDisposalItemSnapshot(item.snapshot_json)
|
||||
if (!snapshot) {
|
||||
throw new DisposalConflictError(`资产 ${item.equipment_code} 的报废快照无法读取,请先核查`)
|
||||
}
|
||||
if (snapshot.total_quantity === undefined) {
|
||||
if (!confirmation) {
|
||||
throw new DisposalConflictError(`资产 ${item.equipment_code} 的历史报废申请未记录数量,请由审批人逐件核对并确认`)
|
||||
}
|
||||
await tx.disposalItem.update({ where: { id: item.id }, data: {
|
||||
snapshot_json: JSON.stringify({ ...snapshot, total_quantity, remaining_quantity })
|
||||
} })
|
||||
restoredSnapshot = true
|
||||
} else if (snapshot.total_quantity !== total_quantity ||
|
||||
(snapshot.remaining_quantity !== undefined && snapshot.remaining_quantity !== remaining_quantity)) {
|
||||
throw new DisposalConflictError(`资产 ${item.equipment_code} 的数量与报废快照不一致,请先核查`)
|
||||
}
|
||||
}
|
||||
return restoredSnapshot
|
||||
}
|
||||
|
||||
const assertConfirmedDisposalQuantities = (
|
||||
items: Array<Pick<DisposalTreeItem, 'id' | 'equipment_code' | 'total_quantity'>>,
|
||||
confirmation: Map<number, number>
|
||||
) => {
|
||||
if (confirmation.size !== items.length) {
|
||||
throw new DisposalConflictError('确认数量的资产范围已变化,请刷新后逐件核对')
|
||||
}
|
||||
const changed = items.find(item => confirmation.get(item.id) !== item.total_quantity)
|
||||
if (changed) {
|
||||
throw new DisposalConflictError(`资产 ${changed.equipment_code} 的数量与本次确认不一致,请刷新后重新核对`)
|
||||
}
|
||||
}
|
||||
|
||||
const readConfirmedDisposalQuantities = (input: unknown) => {
|
||||
if (!Array.isArray(input) || input.length === 0) {
|
||||
throw Object.assign(new Error('请逐件确认报废资产数量'), { status: 422 })
|
||||
}
|
||||
const confirmed = new Map<number, number>()
|
||||
for (const item of input) {
|
||||
const id = item?.equipment_id
|
||||
const quantity = item?.total_quantity
|
||||
if (!Number.isSafeInteger(id) || id < 1 || !Number.isSafeInteger(quantity) || quantity < 1 || confirmed.has(id)) {
|
||||
throw Object.assign(new Error('报废数量确认无效,每件资产须提供唯一 ID 和正整数数量'), { status: 422 })
|
||||
}
|
||||
confirmed.set(id, quantity)
|
||||
}
|
||||
return confirmed
|
||||
}
|
||||
|
||||
export const approveDisposal = async (req: Request, res: Response) => {
|
||||
try {
|
||||
const disposalId = Number(req.params.id)
|
||||
const { approved, reject_reason } = req.body as { approved?: boolean; reject_reason?: string }
|
||||
const { approved, reject_reason, confirmed_quantities, reconfirm_quantities } = req.body as {
|
||||
approved?: boolean
|
||||
reject_reason?: string
|
||||
confirmed_quantities?: unknown
|
||||
reconfirm_quantities?: boolean
|
||||
}
|
||||
const userId = Number(res.locals.user?.id)
|
||||
if (typeof approved !== 'boolean') {
|
||||
return errorResponse(res, '审批结果必须明确为通过或驳回', 422)
|
||||
@ -662,22 +772,32 @@ export const approveDisposal = async (req: Request, res: Response) => {
|
||||
if (!approved && !reject_reason?.trim()) {
|
||||
return errorResponse(res, '驳回原因不能为空', 422)
|
||||
}
|
||||
if (reconfirm_quantities === true && !approved) {
|
||||
return errorResponse(res, '数量复核必须明确确认通过', 422)
|
||||
}
|
||||
const confirmation = approved && (confirmed_quantities !== undefined || reconfirm_quantities === true)
|
||||
? readConfirmedDisposalQuantities(confirmed_quantities) : undefined
|
||||
|
||||
if (reconfirm_quantities === true) {
|
||||
await prisma.$transaction(async tx => {
|
||||
const disposal = await loadLockedDisposalDecision(tx, disposalId, 'approved')
|
||||
if (!await verifyDisposalQuantities(tx, disposal, confirmation)) {
|
||||
throw new DisposalConflictError('该报废单已记录数量,请刷新后查看')
|
||||
}
|
||||
await tx.disposalAction.create({ data: {
|
||||
disposal_id: disposalId, operator_id: userId, action_type: 'quantity_confirmed',
|
||||
from_status: 'approved', to_status: 'approved',
|
||||
detail: JSON.stringify(disposal.items.map(item => ({
|
||||
equipment_id: item.equipment_id, total_quantity: item.equipment.total_quantity
|
||||
})))
|
||||
} })
|
||||
}, { isolationLevel: Prisma.TransactionIsolationLevel.ReadCommitted })
|
||||
return successResponse(res, null, '报废数量已复核')
|
||||
}
|
||||
|
||||
const result = await prisma.$transaction(async (tx) => {
|
||||
const disposal = await tx.disposalRecord.findUnique({
|
||||
where: { id: disposalId },
|
||||
include: { items: { include: { equipment: true } } }
|
||||
})
|
||||
if (!disposal) throw Object.assign(new Error('报废记录不存在'), { status: 404 })
|
||||
const changedItem = disposal.items.find((item) =>
|
||||
item.equipment.status !== '待报废' ||
|
||||
item.equipment.parent_id !== item.parent_equipment_id
|
||||
)
|
||||
if (changedItem) {
|
||||
throw new DisposalConflictError(
|
||||
`资产 ${changedItem.equipment_code} 的状态或挂载关系已变化,请先核查`
|
||||
)
|
||||
}
|
||||
const disposal = await loadLockedDisposalDecision(tx, disposalId, 'pending')
|
||||
if (approved) await verifyDisposalQuantities(tx, disposal, confirmation)
|
||||
|
||||
const nextStatus = approved ? 'approved' : 'rejected'
|
||||
const approvedAt = new Date()
|
||||
@ -755,7 +875,7 @@ export const approveDisposal = async (req: Request, res: Response) => {
|
||||
}
|
||||
})
|
||||
return disposal
|
||||
})
|
||||
}, { isolationLevel: Prisma.TransactionIsolationLevel.ReadCommitted })
|
||||
|
||||
await logOperation(
|
||||
userId,
|
||||
@ -783,11 +903,8 @@ export const completeDisposal = async (req: Request, res: Response) => {
|
||||
}
|
||||
|
||||
const result = await prisma.$transaction(async (tx) => {
|
||||
const disposal = await tx.disposalRecord.findUnique({
|
||||
where: { id: disposalId },
|
||||
include: { items: { include: { equipment: true } } }
|
||||
})
|
||||
if (!disposal) throw Object.assign(new Error('报废记录不存在'), { status: 404 })
|
||||
const disposal = await loadLockedDisposalDecision(tx, disposalId, 'approved')
|
||||
await verifyDisposalQuantities(tx, disposal)
|
||||
|
||||
const completedAt = new Date()
|
||||
const updated = await tx.disposalRecord.updateMany({
|
||||
@ -850,7 +967,7 @@ export const completeDisposal = async (req: Request, res: Response) => {
|
||||
}
|
||||
})
|
||||
return disposal
|
||||
})
|
||||
}, { isolationLevel: Prisma.TransactionIsolationLevel.ReadCommitted })
|
||||
|
||||
await logOperation(
|
||||
userId,
|
||||
|
||||
@ -6,9 +6,9 @@ import {
|
||||
calculateEquipmentValues,
|
||||
deriveParentBaseUnitPrice,
|
||||
refreshParentTotalValueWithChildren,
|
||||
sumBundleChildrenValue,
|
||||
syncMountedChildrenState
|
||||
sumBundleChildrenValue
|
||||
} from '../utils/assetValue'
|
||||
import { AssetTreeConflictError, loadAndLockAssetTree, lockEquipmentRows } from '../services/assetMovementService'
|
||||
import { getBorrowAnomalyMeta } from '../utils/borrowAnomaly'
|
||||
import { getEquipmentDeleteBlockedReason } from '../utils/equipmentDeletion'
|
||||
import { buildSyncedBusinessDepartmentWhere } from '../utils/organization'
|
||||
@ -1211,7 +1211,8 @@ export const updateEquipment = async (req: Request, res: Response) => {
|
||||
) {
|
||||
return errorResponse(res, '资产总数量必须是大于或等于 1 的整数', 422)
|
||||
}
|
||||
if (currentEquipment.status === '已丢失' && finalTotalQuantity !== currentEquipment.total_quantity) {
|
||||
const quantityChanged = finalTotalQuantity !== currentEquipment.total_quantity
|
||||
if (currentEquipment.status === '已丢失' && quantityChanged) {
|
||||
return errorResponse(res, '已丢失资产不能修改库存数量,请先人工核实台账', 409)
|
||||
}
|
||||
const finalUnitPrice = unit_price !== undefined ? Number(unit_price) : Number(currentEquipment.unit_price)
|
||||
@ -1219,14 +1220,14 @@ export const updateEquipment = async (req: Request, res: Response) => {
|
||||
const borrowedQuantity = Math.max(currentEquipment.total_quantity - currentEquipment.remaining_quantity, 0)
|
||||
// 若修改了总库存,则根据已借数量同步计算新的剩余库存;否则保持原剩余库存
|
||||
const newRemainingQuantity =
|
||||
total_quantity !== undefined
|
||||
quantityChanged
|
||||
? Math.max(finalTotalQuantity - borrowedQuantity, 0)
|
||||
: currentEquipment.remaining_quantity
|
||||
const resolvedStatus = resolveEditableEquipmentStatus({
|
||||
const resolvedStatus = quantityChanged ? resolveEditableEquipmentStatus({
|
||||
currentStatus: currentEquipment.status,
|
||||
requestedStatus: status,
|
||||
remainingQuantity: newRemainingQuantity
|
||||
})
|
||||
}) : currentEquipment.status
|
||||
if (currentRole === 'administrative' && resolvedStatus !== '可用') {
|
||||
return errorResponse(
|
||||
res,
|
||||
@ -1274,7 +1275,7 @@ export const updateEquipment = async (req: Request, res: Response) => {
|
||||
correctionUpdateData.borrowed_value = values.borrowed_value
|
||||
correctionUpdateData.available_value = values.available_value
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(req.body, 'total_quantity')) {
|
||||
if (quantityChanged) {
|
||||
correctionUpdateData.total_quantity = finalTotalQuantity
|
||||
correctionUpdateData.remaining_quantity = newRemainingQuantity
|
||||
correctionUpdateData.status = resolvedStatus
|
||||
@ -1293,9 +1294,37 @@ export const updateEquipment = async (req: Request, res: Response) => {
|
||||
}
|
||||
|
||||
const updated = await prisma.$transaction(async (tx) => {
|
||||
await tx.$queryRawUnsafe(
|
||||
`SELECT id FROM equipment WHERE id = ${currentEquipment.id} FOR UPDATE`
|
||||
)
|
||||
if (quantityChanged) {
|
||||
const tree = await loadAndLockAssetTree(tx, currentEquipment.parent_id ?? currentEquipment.id)
|
||||
const locked = tree.find(item => item.id === currentEquipment.id)
|
||||
if (!locked || locked.total_quantity !== currentEquipment.total_quantity ||
|
||||
locked.remaining_quantity !== currentEquipment.remaining_quantity || locked.status !== currentEquipment.status ||
|
||||
locked.parent_id !== currentEquipment.parent_id || locked.updated_at.getTime() !== currentEquipment.updated_at.getTime()) return false
|
||||
|
||||
const ids = tree.map(item => item.id)
|
||||
const [loans, disposal] = await Promise.all([
|
||||
tx.borrowRecord.findMany({ where: { equipment_id: { in: ids }, status: '已借出' }, select: { equipment_id: true, return_time: true } }),
|
||||
tx.disposalRecord.findFirst({ where: { status: { in: ['pending', 'approved'] }, OR: [
|
||||
{ equipment_id: { in: ids } }, { items: { some: { equipment_id: { in: ids } } } }
|
||||
] }, select: { id: true } })
|
||||
])
|
||||
if (disposal || tree.some(item => item.status === '待报废')) {
|
||||
throw new AssetTreeConflictError('资产存在待审批或已审批的报废申请,不能修改数量')
|
||||
}
|
||||
if (locked.parent_id !== null && (locked.status === '已借出' || loans.length > 0)) {
|
||||
throw new AssetTreeConflictError('挂载资产仍有借用占用,不能修改数量')
|
||||
}
|
||||
const ownLoans = loans.filter(loan => loan.equipment_id === locked.id && loan.return_time === null).length
|
||||
if (locked.remaining_quantity < 0 || locked.remaining_quantity > locked.total_quantity ||
|
||||
(locked.status === '可用' && locked.remaining_quantity === 0) ||
|
||||
(locked.status === '已借出' && (locked.remaining_quantity !== 0 || ownLoans === 0)) ||
|
||||
locked.total_quantity - locked.remaining_quantity !== ownLoans || loans.length !== ownLoans) {
|
||||
throw new AssetTreeConflictError('资产库存、状态与实际未归还记录不一致,请先核查')
|
||||
}
|
||||
if (finalTotalQuantity < ownLoans) throw new AssetTreeConflictError('资产总数量不能小于实际未归还数量')
|
||||
} else {
|
||||
await lockEquipmentRows(tx, [currentEquipment.parent_id ?? currentEquipment.id, currentEquipment.id])
|
||||
}
|
||||
|
||||
await ensureAdministrativeCorrectionAllowed(req, currentEquipment, tx, currentRole)
|
||||
if (assetTypeChangeRequested) {
|
||||
@ -1345,18 +1374,6 @@ export const updateEquipment = async (req: Request, res: Response) => {
|
||||
where: { parent_id: Number(id) }
|
||||
})
|
||||
|
||||
if (
|
||||
childCount > 0 &&
|
||||
['可用', '已借出', '维护中', '待报废', '已报废'].includes(resolvedStatus) &&
|
||||
Object.prototype.hasOwnProperty.call(updateData, 'status')
|
||||
) {
|
||||
await syncMountedChildrenState(
|
||||
tx,
|
||||
Number(id),
|
||||
resolvedStatus as '可用' | '已借出' | '维护中' | '待报废' | '已报废'
|
||||
)
|
||||
}
|
||||
|
||||
if (childCount > 0) {
|
||||
await refreshParentTotalValueWithChildren(tx, Number(id))
|
||||
}
|
||||
@ -1379,7 +1396,7 @@ export const updateEquipment = async (req: Request, res: Response) => {
|
||||
})
|
||||
|
||||
return true
|
||||
})
|
||||
}, { isolationLevel: 'ReadCommitted' })
|
||||
|
||||
if (!updated) {
|
||||
return errorResponse(res, '资产状态、部门或挂载关系已变化,请刷新后重试', 409)
|
||||
@ -1392,7 +1409,7 @@ export const updateEquipment = async (req: Request, res: Response) => {
|
||||
|
||||
successResponse(res, equipment, '更新成功')
|
||||
} catch (error: any) {
|
||||
const statusCode = error.statusCode || (error.code === 'P2002' ? 409 : 400)
|
||||
const statusCode = error.statusCode || error.status || (error.code === 'P2002' ? 409 : 400)
|
||||
errorResponse(res, error.message || '更新资产失败', statusCode)
|
||||
}
|
||||
}
|
||||
|
||||
@ -172,7 +172,7 @@ export const assignInventoryTaskUnassignedController = async (req: Request, res:
|
||||
successResponse(res, null, '分配成功')
|
||||
} catch (error: any) {
|
||||
const message = error.message || '分配无人归属资产失败'
|
||||
errorResponse(res, message, message.includes('不存在') ? 404 : 422)
|
||||
errorResponse(res, message, error.status || (message.includes('不存在') ? 404 : 422))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -14,6 +14,11 @@ import {
|
||||
} from '../services/inventoryService'
|
||||
|
||||
const INVENTORY_SESSION_KEY = 'inventoryParticipant'
|
||||
const inventorySessionError = (message: string, status = 401) => Object.assign(new Error(message), { status })
|
||||
const respondInventoryError = (res: Response, error: { message?: string; status?: number }, fallback: string) => {
|
||||
const status = error.status || 500
|
||||
errorResponse(res, status === 500 ? fallback : error.message || fallback, status)
|
||||
}
|
||||
|
||||
const getInventorySession = (req: Request) => (((req as any).session as any)?.[INVENTORY_SESSION_KEY] || null) as
|
||||
| {
|
||||
@ -44,7 +49,7 @@ const ensureCurrentInventoryIdentity = async (req: Request, participantPersonId:
|
||||
const sessionUser = ((req as any).session as any)?.user
|
||||
const userId = Number(sessionUser?.id)
|
||||
if (!Number.isInteger(userId) || userId <= 0) {
|
||||
throw new Error('请重新使用钉钉登录后进入盘点任务')
|
||||
throw inventorySessionError('请重新使用钉钉登录后进入盘点任务')
|
||||
}
|
||||
|
||||
if (sessionUser?.auth_source === 'dingtalk') {
|
||||
@ -52,7 +57,7 @@ const ensureCurrentInventoryIdentity = async (req: Request, participantPersonId:
|
||||
const eligibleUser = await findEligibleDingTalkSessionUser(userId, dingtalkUserId)
|
||||
if (!eligibleUser) {
|
||||
;((req as any).session as any).user = undefined
|
||||
throw new Error('钉钉身份或员工绑定已失效,请重新登录')
|
||||
throw inventorySessionError('钉钉身份或员工绑定已失效,请重新登录')
|
||||
}
|
||||
}
|
||||
|
||||
@ -62,27 +67,44 @@ const ensureCurrentInventoryIdentity = async (req: Request, participantPersonId:
|
||||
currentUser.person_id !== participantPersonId ||
|
||||
currentUser.person?.status !== 'active'
|
||||
) {
|
||||
throw new Error('当前登录账号与盘点责任人不一致,请重新进入本人任务')
|
||||
throw inventorySessionError('当前登录账号与盘点责任人不一致,请重新进入本人任务')
|
||||
}
|
||||
}
|
||||
|
||||
const ensureInventorySession = async (req: Request) => {
|
||||
const ensureInventorySession = async (req: Request, input: 'query' | 'body') => {
|
||||
const expected = req[input]
|
||||
const taskToken = expected?.task_token
|
||||
if (typeof taskToken !== 'string' || !taskToken.trim()) {
|
||||
throw inventorySessionError('盘点任务标识不能为空', 422)
|
||||
}
|
||||
const participantValue = expected?.participant_id
|
||||
const participantId = Number(participantValue)
|
||||
if ((input === 'body' || participantValue !== undefined) &&
|
||||
((typeof participantValue !== 'string' && typeof participantValue !== 'number') ||
|
||||
!Number.isSafeInteger(participantId) || participantId < 1)) {
|
||||
throw inventorySessionError('盘点参与人标识无效', 422)
|
||||
}
|
||||
|
||||
const session = getInventorySession(req)
|
||||
if (!session) {
|
||||
throw new Error('盘点会话不存在,请重新确认身份')
|
||||
throw inventorySessionError('盘点会话不存在,请重新确认身份', 404)
|
||||
}
|
||||
if (session.publicToken !== taskToken || (participantValue !== undefined && session.participantId !== participantId)) {
|
||||
throw inventorySessionError('盘点会话已切换,请重新确认本页身份', 409)
|
||||
}
|
||||
|
||||
const taskContext = await getParticipantTaskContext(session.taskId, session.participantId)
|
||||
if (taskContext.task.public_token !== session.publicToken) {
|
||||
clearInventorySession(req)
|
||||
throw new Error('盘点会话已失效,请重新确认身份')
|
||||
throw inventorySessionError('盘点会话已失效,请重新确认身份')
|
||||
}
|
||||
|
||||
if (taskContext.task.identity_mode === 'dingtalk') {
|
||||
try {
|
||||
await ensureCurrentInventoryIdentity(req, taskContext.participant.person_id)
|
||||
} catch (error) {
|
||||
clearInventorySession(req)
|
||||
const status = (error as { status?: number }).status
|
||||
if (status === 401 || status === 403) clearInventorySession(req)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
@ -156,7 +178,7 @@ export const confirmCurrentInventoryParticipantController = async (req: Request,
|
||||
|
||||
export const getPublicInventoryMeController = async (req: Request, res: Response) => {
|
||||
try {
|
||||
const { task, participant } = await ensureInventorySession(req)
|
||||
const { task, participant } = await ensureInventorySession(req, 'query')
|
||||
successResponse(
|
||||
res,
|
||||
{
|
||||
@ -178,25 +200,23 @@ export const getPublicInventoryMeController = async (req: Request, res: Response
|
||||
'获取成功'
|
||||
)
|
||||
} catch (error: any) {
|
||||
const message = error.message || '获取盘点会话失败'
|
||||
errorResponse(res, message, message.includes('不存在') ? 404 : 401)
|
||||
respondInventoryError(res, error, '获取盘点会话失败')
|
||||
}
|
||||
}
|
||||
|
||||
export const getPublicInventoryItemsController = async (req: Request, res: Response) => {
|
||||
try {
|
||||
const { task, participant } = await ensureInventorySession(req)
|
||||
const { task, participant } = await ensureInventorySession(req, 'query')
|
||||
const data = await getParticipantItems(task.id, participant.id)
|
||||
successResponse(res, data, '获取成功')
|
||||
} catch (error: any) {
|
||||
const message = error.message || '获取盘点资产失败'
|
||||
errorResponse(res, message, message.includes('不存在') ? 404 : 401)
|
||||
respondInventoryError(res, error, '获取盘点资产失败')
|
||||
}
|
||||
}
|
||||
|
||||
export const submitPublicInventoryScanController = async (req: Request, res: Response) => {
|
||||
try {
|
||||
const { task, participant } = await ensureInventorySession(req)
|
||||
const { task, participant } = await ensureInventorySession(req, 'body')
|
||||
if (task.status === 'closed') {
|
||||
return errorResponse(res, '盘点任务已关闭', 403)
|
||||
}
|
||||
@ -209,18 +229,13 @@ export const submitPublicInventoryScanController = async (req: Request, res: Res
|
||||
const data = await submitInventoryScan(task.id, participant.id, equipmentCode)
|
||||
successResponse(res, data, '盘点成功')
|
||||
} catch (error: any) {
|
||||
const message = error.message || '提交盘点结果失败'
|
||||
errorResponse(
|
||||
res,
|
||||
message,
|
||||
message.includes('盘点范围') || message.includes('不能为空') ? 422 : message.includes('不存在') ? 404 : 401
|
||||
)
|
||||
respondInventoryError(res, error, '提交盘点结果失败')
|
||||
}
|
||||
}
|
||||
|
||||
export const submitPublicInventoryExceptionController = async (req: Request, res: Response) => {
|
||||
try {
|
||||
const { task, participant } = await ensureInventorySession(req)
|
||||
const { task, participant } = await ensureInventorySession(req, 'body')
|
||||
if (task.status === 'closed') {
|
||||
return errorResponse(res, '盘点任务已关闭', 403)
|
||||
}
|
||||
@ -239,11 +254,6 @@ export const submitPublicInventoryExceptionController = async (req: Request, res
|
||||
)
|
||||
successResponse(res, null, '异常已提交')
|
||||
} catch (error: any) {
|
||||
const message = error.message || '提交盘点异常失败'
|
||||
errorResponse(
|
||||
res,
|
||||
message,
|
||||
message.includes('不存在') ? 404 : message.includes('无效') ? 422 : 401
|
||||
)
|
||||
respondInventoryError(res, error, '提交盘点异常失败')
|
||||
}
|
||||
}
|
||||
|
||||
@ -113,6 +113,7 @@ test('新盘点任务后续请求持续核验当前账号与盘点责任人一
|
||||
}
|
||||
}
|
||||
const request = {
|
||||
query: { task_token: 'public-task-token' },
|
||||
session: {
|
||||
user: { id: 9 },
|
||||
inventoryParticipant: {
|
||||
|
||||
@ -328,8 +328,8 @@ export const borrowAssetTree = async (
|
||||
)
|
||||
|
||||
const equipmentIds = items.map((item) => item.id)
|
||||
const activeBorrowRows = await client.$queryRaw<Array<{ id: number; equipment_id: number }>>(Prisma.sql`
|
||||
SELECT id, equipment_id
|
||||
const activeBorrowRows = await client.$queryRaw<Array<{ id: number; equipment_id: number; person_id: number; return_time: Date | null }>>(Prisma.sql`
|
||||
SELECT id, equipment_id, person_id, return_time
|
||||
FROM borrow_record
|
||||
WHERE equipment_id IN (${Prisma.join(equipmentIds)}) AND status = ${'已借出'}
|
||||
ORDER BY id
|
||||
@ -339,7 +339,7 @@ export const borrowAssetTree = async (
|
||||
(row) => Number(row.equipment_id) === root.id
|
||||
).length
|
||||
const expectedRootBorrowCount = root.total_quantity - root.remaining_quantity
|
||||
if (rootActiveBorrowCount !== expectedRootBorrowCount) {
|
||||
if (rootActiveBorrowCount !== expectedRootBorrowCount || activeBorrowRows.some(row => row.return_time)) {
|
||||
throw new AssetTreeConflictError('主资产库存与未归还借用记录不一致,请先核查')
|
||||
}
|
||||
const occupiedChild = activeBorrowRows.find((row) => Number(row.equipment_id) !== root.id)
|
||||
@ -372,16 +372,21 @@ export const borrowAssetTree = async (
|
||||
|
||||
// Recheck the person after locking the asset tree, as HR sync can deactivate
|
||||
// them between the controller's lookup and the transaction.
|
||||
const personIds = [...new Set([input.person.id, ...activeBorrowRows.map(row => row.person_id)])].sort((left, right) => left - right)
|
||||
const people = await client.$queryRaw<Array<{
|
||||
id: number; real_name: string; nickname: string; job_number: string | null;
|
||||
status: string; main_department_id: number | null
|
||||
}>>(Prisma.sql`SELECT id, real_name, nickname, job_number, status, main_department_id
|
||||
FROM person WHERE id = ${input.person.id} FOR UPDATE`)
|
||||
const borrowPerson = people[0]
|
||||
FROM person WHERE id IN (${Prisma.join(personIds)}) ORDER BY id FOR UPDATE`)
|
||||
const borrowPerson = people.find(person => person.id === input.person.id)
|
||||
if (!borrowPerson || borrowPerson.status !== 'active') {
|
||||
throw new AssetTreeConflictError('使用者已失效,请刷新人员后重试')
|
||||
}
|
||||
let targetDepartmentId = borrowPerson.main_department_id ?? root.department_id
|
||||
if (rootActiveBorrowCount > 0 && (people.length !== personIds.length || targetDepartmentId !== root.department_id ||
|
||||
people.some(person => (person.main_department_id ?? root.department_id) !== targetDepartmentId))) {
|
||||
throw new AssetTreeConflictError('该资产已有不同部门或归属不一致的未归还记录,不能继续借用')
|
||||
}
|
||||
let correctionOperator: { id: number; username: string } | undefined
|
||||
let correctionDepartmentName: string | undefined
|
||||
if (inconsistentDepartment) {
|
||||
|
||||
@ -1441,7 +1441,7 @@ export const getParticipantTaskContext = async (taskId: number, participantId: n
|
||||
])
|
||||
|
||||
if (!task || !participant) {
|
||||
throw new Error('盘点任务会话已失效')
|
||||
throw Object.assign(new Error('盘点任务会话已失效'), { status: 404 })
|
||||
}
|
||||
|
||||
return {
|
||||
@ -1491,7 +1491,7 @@ const updateTaskItemStatus = async (
|
||||
const item = await tx.inventoryTaskItem.findFirst({
|
||||
where: { id: itemId, task_id: taskId, participant_id: participantId }
|
||||
})
|
||||
if (!item) throw new Error('盘点资产不在当前人员范围内')
|
||||
if (!item) throw Object.assign(new Error('盘点资产不在当前人员范围内'), { status: 422 })
|
||||
const updated = await tx.inventoryTaskItem.update({
|
||||
where: { id: itemId },
|
||||
data: {
|
||||
@ -1518,12 +1518,12 @@ const updateTaskItemStatus = async (
|
||||
|
||||
export const submitInventoryScan = async (taskId: number, participantId: number, equipmentCode: string) => {
|
||||
const normalizedCode = equipmentCode.trim()
|
||||
if (!normalizedCode) throw new Error('资产编码不能为空')
|
||||
if (!normalizedCode) throw Object.assign(new Error('资产编码不能为空'), { status: 422 })
|
||||
const item = await prisma.inventoryTaskItem.findFirst({
|
||||
where: { task_id: taskId, equipment_code: normalizedCode }
|
||||
})
|
||||
if (!item) throw new Error('该资产不在本次盘点任务范围内')
|
||||
if (item.participant_id !== participantId) throw new Error('该资产不在你的盘点范围内')
|
||||
if (!item) throw Object.assign(new Error('该资产不在本次盘点任务范围内'), { status: 422 })
|
||||
if (item.participant_id !== participantId) throw Object.assign(new Error('该资产不在你的盘点范围内'), { status: 422 })
|
||||
return updateTaskItemStatus(taskId, participantId, item.id, {
|
||||
check_status: INVENTORY_ITEM_CHECK_STATUS.checked,
|
||||
exception_type: null, exception_note: null,
|
||||
@ -1535,7 +1535,7 @@ export const submitInventoryException = async (
|
||||
taskId: number, participantId: number, itemId: number,
|
||||
exceptionType: string, exceptionNote?: string | null
|
||||
) => {
|
||||
if (!['not_found', 'not_with_me'].includes(exceptionType)) throw new Error('异常类型无效')
|
||||
if (!['not_found', 'not_with_me'].includes(exceptionType)) throw Object.assign(new Error('异常类型无效'), { status: 422 })
|
||||
return updateTaskItemStatus(taskId, participantId, itemId, {
|
||||
check_status: INVENTORY_ITEM_CHECK_STATUS.exception,
|
||||
exception_type: exceptionType, exception_note: exceptionNote?.trim() || null,
|
||||
@ -1700,6 +1700,9 @@ export const assignUnassignedTaskItem = async (
|
||||
await lockOpenInventoryTask(tx, taskId)
|
||||
const item = await tx.inventoryTaskItem.findFirst({ where: { id: itemId, task_id: taskId } })
|
||||
if (!item || !item.is_unassigned) throw new Error('待处理资产不存在或已被分配,请刷新后重试')
|
||||
if (item.check_status !== INVENTORY_ITEM_CHECK_STATUS.pending) {
|
||||
throw Object.assign(new Error('该资产已核验,不能重新分配,请刷新后查看'), { status: 409 })
|
||||
}
|
||||
let participant = await tx.inventoryTaskParticipant.findFirst({
|
||||
where: {
|
||||
task_id: taskId,
|
||||
|
||||
@ -77,6 +77,8 @@ export const getDisposalBlockedReason = (tree: DisposalTreeItem[], occupancy?: A
|
||||
if (tree.some(item => occupancy?.borrowed.has(item.id))) return '资产树存在未归还记录,不能申请报废'
|
||||
if (tree.some(item => occupancy?.maintenance.has(item.id))) return '资产树存在进行中的维修,请先完成或取消维修'
|
||||
if (tree.some(item => occupancy?.disposal.has(item.id))) return '资产树已有进行中的报废申请'
|
||||
const invalidInventory = tree.find(item => item.total_quantity < 1 || item.remaining_quantity !== item.total_quantity)
|
||||
if (invalidInventory) return `资产 ${invalidInventory.equipment_code} 库存与报废数量不一致,请先核查`
|
||||
return null
|
||||
}
|
||||
|
||||
|
||||
@ -56,7 +56,7 @@ assert.equal(byDepartment.length, 1, '搜索部门时应排除已停用人员')
|
||||
assert.equal(byDepartment[0].id, 1, '部门搜索结果不正确')
|
||||
|
||||
const byPhone = filterManualBorrowPersons(samplePersons as any, '0002')
|
||||
assert.equal(byPhone[0].id, 2, '手机号搜索应支持辅助定位')
|
||||
assert.equal(byPhone.length, 0, '手机号不参与借用人员搜索')
|
||||
|
||||
const preferredExact = findPreferredManualBorrowPerson(byNickname as any, '阿杰')
|
||||
assert.equal(preferredExact?.id, 1, '精确匹配时应支持直接选中')
|
||||
|
||||
339
frontend/scripts/test-scan-request-order.mjs
Normal file
339
frontend/scripts/test-scan-request-order.mjs
Normal file
@ -0,0 +1,339 @@
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import fs from 'node:fs'
|
||||
import ts from 'typescript'
|
||||
import { computed, effectScope, nextTick, reactive, ref, watch } from 'vue'
|
||||
import { createRequestScope } from '../src/utils/requestScope.ts'
|
||||
import { submitReturnWithConfirmation, getReturnCompletionText } from '../src/utils/returnConfirmation.ts'
|
||||
import { canSubmitBorrowScan } from '../src/views/borrow/borrowScanState.ts'
|
||||
import { canSubmitReturnScan } from '../src/views/borrow/returnScanState.ts'
|
||||
|
||||
const deferred = () => {
|
||||
let resolve
|
||||
let reject
|
||||
const promise = new Promise((done, fail) => { resolve = done; reject = fail })
|
||||
return { promise, resolve, reject }
|
||||
}
|
||||
const turn = () => new Promise((resolve) => setImmediate(resolve))
|
||||
const quiet = () => {}
|
||||
|
||||
function component(t, filename, names, bindings = {}) {
|
||||
const source = fs.readFileSync(new URL('../src/views/' + filename, import.meta.url), 'utf8')
|
||||
const script = source.match(/<script setup lang="ts">([\s\S]*?)<\/script>/)[1]
|
||||
const parsed = ts.createSourceFile(filename + '.ts', script, ts.ScriptTarget.ES2020, true)
|
||||
const body = parsed.statements.filter((node) => !ts.isImportDeclaration(node)).map((node) => node.getText()).join('\n')
|
||||
const code = ts.transpileModule(body, { compilerOptions: { target: ts.ScriptTarget.ES2020 } }).outputText
|
||||
const route = reactive({ query: {}, params: { token: 'fixture-task' } })
|
||||
const disposalCallbacks = []
|
||||
const scope = effectScope()
|
||||
const context = {
|
||||
computed, ref, watch, reactive, nextTick, createRequestScope, canSubmitBorrowScan, canSubmitReturnScan,
|
||||
submitReturnWithConfirmation, getReturnCompletionText,
|
||||
onMounted: quiet, onUnmounted: (callback) => disposalCallbacks.push(callback),
|
||||
useRoute: () => route, useAuthStore: () => ({}),
|
||||
isPublicInventorySessionChanged: (error) => error?.status === 409 && error.message === '盘点会话已切换,请重新确认本页身份',
|
||||
window: { matchMedia: () => ({ matches: true }), setTimeout, clearTimeout, confirm: () => true },
|
||||
playBeepSound: quiet, playErrorSound: quiet,
|
||||
buildManualBorrowPersonDisplay: (person) => person.nickname,
|
||||
isManualBorrowSelectedPersonKeyword: (person, keyword) => person.nickname === keyword,
|
||||
buildManualReturnRecordDisplay: (record) => record.person_nickname,
|
||||
isManualReturnSelectedRecordKeyword: (record, keyword) => record.person_nickname === keyword,
|
||||
...bindings
|
||||
}
|
||||
t.after(() => { disposalCallbacks.forEach((dispose) => dispose()); scope.stop() })
|
||||
return scope.run(() => new Function(...Object.keys(context), code + '\nreturn { route, ' + names.join(', ') + ' };')(...Object.values(context)))
|
||||
}
|
||||
|
||||
const borrower = { id: 7, nickname: '使用者甲', real_name: '甲' }
|
||||
const equipment = (code, id) => ({ id, equipment_code: code, equipment_name: '资产 ' + code, status: '可用' })
|
||||
const record = (code, id, recordId) => ({
|
||||
id: recordId, equipment_id: id, person_id: borrower.id, person_nickname: borrower.nickname,
|
||||
equipment_code: code
|
||||
})
|
||||
const returnData = (code, id, recordId) => ({ data: { equipment_code: code, equipment_name: '资产 ' + code, borrow_records: [record(code, id, recordId)] } })
|
||||
|
||||
test('borrow scans leave the newer asset and its accessories in place when an older child lookup finishes', async (t) => {
|
||||
const olderChildren = deferred()
|
||||
const view = component(t, 'borrow/BorrowScan.vue', [
|
||||
'handleScan', 'handleCameraDetected', 'selectManualSearchResult', 'equipmentInfo', 'mountedChildren', 'lookupLoading', 'canSubmit'
|
||||
], {
|
||||
scanEquipment: async (code) => ({ data: equipment(code, code === 'A' ? 1 : 2) }),
|
||||
getChildren: async (id) => id === 1 ? olderChildren.promise : { data: { children: [{ id: 22 }], total_children_value: 10 } }
|
||||
})
|
||||
const old = view.selectManualSearchResult(equipment('A', 1))
|
||||
await turn()
|
||||
assert.equal(view.lookupLoading.value, true)
|
||||
assert.equal(view.equipmentInfo.value, null)
|
||||
assert.equal(view.canSubmit.value, false)
|
||||
await view.handleCameraDetected('B')
|
||||
olderChildren.resolve({ data: { children: [{ id: 11 }], total_children_value: 20 } })
|
||||
await old
|
||||
assert.equal(view.equipmentInfo.value.equipment_code, 'B')
|
||||
assert.deepEqual(view.mountedChildren.value.map((child) => child.id), [22])
|
||||
assert.equal(view.lookupLoading.value, false)
|
||||
})
|
||||
|
||||
test('a late borrow lookup failure cannot replace a newer successful prefilled result', async (t) => {
|
||||
const old = deferred()
|
||||
const view = component(t, 'borrow/BorrowScan.vue', ['handleCameraDetected', 'equipmentInfo', 'scanError'], {
|
||||
scanEquipment: (code) => code === 'A' ? old.promise : Promise.resolve({ data: equipment(code, 2) }),
|
||||
getChildren: async () => ({ data: { children: [], total_children_value: 0 } })
|
||||
})
|
||||
const pending = view.handleCameraDetected('A')
|
||||
view.route.query = { equipment_code: 'B' }
|
||||
await turn()
|
||||
old.reject(new Error('A lookup failed'))
|
||||
await pending
|
||||
assert.equal(view.equipmentInfo.value.equipment_code, 'B')
|
||||
assert.equal(view.scanError.value, '')
|
||||
})
|
||||
|
||||
test('borrow submit clears the old draft during new lookup and freezes the confirmed asset and person during the write', async (t) => {
|
||||
const newAsset = deferred()
|
||||
const pendingWrite = deferred()
|
||||
const submissions = []
|
||||
const lookups = []
|
||||
const view = component(t, 'borrow/BorrowScan.vue', [
|
||||
'handleScan', 'handleSubmit', 'selectPerson', 'persons', 'selectedPersonId', 'borrowForm', 'successInfo', 'loading'
|
||||
], {
|
||||
scanEquipment: async (code) => { lookups.push(code); return code === 'B' ? newAsset.promise : { data: equipment(code, 1) } },
|
||||
getChildren: async () => ({ data: { children: [], total_children_value: 0 } }),
|
||||
scanBorrow: (payload) => { submissions.push(payload); return pendingWrite.promise }
|
||||
})
|
||||
view.persons.value = [borrower]
|
||||
await view.handleScan('A')
|
||||
view.selectPerson(borrower)
|
||||
const lookup = view.handleScan('B')
|
||||
await view.handleSubmit()
|
||||
assert.equal(submissions.length, 0)
|
||||
newAsset.resolve({ data: equipment('B', 2) })
|
||||
await lookup
|
||||
view.selectPerson(borrower)
|
||||
view.borrowForm.value.notes = '已确认备注'
|
||||
const write = view.handleSubmit()
|
||||
assert.equal(view.loading.value, true)
|
||||
await view.handleSubmit()
|
||||
await view.handleScan('C')
|
||||
view.selectPerson({ id: 8, nickname: '使用者乙' })
|
||||
assert.equal(view.selectedPersonId.value, 7)
|
||||
assert.deepEqual(lookups, ['A', 'B'])
|
||||
assert.deepEqual(submissions.map((row) => [row.equipment_code, row.person_id, row.notes]), [['B', 7, '已确认备注']])
|
||||
pendingWrite.resolve({ data: { borrow_time: '2026-11-10T00:00:00Z' } })
|
||||
await write
|
||||
assert.equal(view.successInfo.value.equipment_code, 'B')
|
||||
assert.match(view.successInfo.value.person_display, /使用者甲/)
|
||||
})
|
||||
|
||||
test('return scan keeps the new asset and borrow record after the older anomaly fallback finishes', async (t) => {
|
||||
const fallback = deferred()
|
||||
const view = component(t, 'borrow/ReturnScan.vue', [
|
||||
'handleCameraDetected', 'borrowRecordInfo', 'selectedBorrowRecordId', 'pageNotice', 'showBorrowAnomalyHandler'
|
||||
], {
|
||||
getBorrowRecordByCode: async (code) => {
|
||||
if (code === 'A') throw Object.assign(new Error('A record missing'), { status: 409 })
|
||||
return returnData(code, 2, 202)
|
||||
},
|
||||
getChildren: async () => ({ data: { children: [] } }),
|
||||
searchReturnAssets: () => fallback.promise,
|
||||
findPreferredManualReturnAssetCandidate: (rows) => rows[0],
|
||||
filterManualReturnAssetCandidates: (rows) => rows
|
||||
})
|
||||
const pending = view.handleCameraDetected('A')
|
||||
await turn()
|
||||
view.route.query = { equipmentCode: 'B', borrowRecordId: '202' }
|
||||
await turn()
|
||||
fallback.resolve({ data: [{ equipment_id: 1, equipment_code: 'A', search_state: 'borrow_record_missing', can_handle_borrow_anomaly: true }] })
|
||||
await pending
|
||||
assert.equal(view.borrowRecordInfo.value.equipment_code, 'B')
|
||||
assert.equal(view.selectedBorrowRecordId.value, 202)
|
||||
assert.equal(view.showBorrowAnomalyHandler.value, false)
|
||||
assert.match(view.pageNotice.value.message, /资产 B/)
|
||||
})
|
||||
|
||||
test('return reads disable stale submission, reject a missing prefilled record, and lock the confirmed transaction', async (t) => {
|
||||
const newerRecord = deferred()
|
||||
const pendingWrite = deferred()
|
||||
const lookups = []
|
||||
const submissions = []
|
||||
const view = component(t, 'borrow/ReturnScan.vue', [
|
||||
'handleScan', 'handleSubmit', 'selectBorrowRecord', 'selectedBorrowRecordId', 'canSubmit', 'returnInfo', 'pageNotice'
|
||||
], {
|
||||
getBorrowRecordByCode: async (code) => { lookups.push(code); return code === 'B' ? newerRecord.promise : returnData(code, 1, 101) },
|
||||
getChildren: async () => ({ data: { children: [] } }),
|
||||
scanReturn: (payload) => { submissions.push(payload); return pendingWrite.promise }
|
||||
})
|
||||
await view.handleScan('A')
|
||||
assert.equal(view.canSubmit.value, true)
|
||||
const lookup = view.handleScan('B', 999)
|
||||
await view.handleSubmit()
|
||||
assert.equal(submissions.length, 0)
|
||||
newerRecord.resolve(returnData('B', 2, 202))
|
||||
await lookup
|
||||
assert.equal(view.canSubmit.value, false)
|
||||
assert.equal(view.selectedBorrowRecordId.value, null)
|
||||
assert.match(view.pageNotice.value.message, /指定借用记录/)
|
||||
view.selectBorrowRecord(record('B', 2, 202))
|
||||
view.returnInfo.value.return_condition = '损坏'
|
||||
const write = view.handleSubmit()
|
||||
await view.handleSubmit()
|
||||
await view.handleScan('C')
|
||||
view.selectBorrowRecord(record('C', 3, 303))
|
||||
assert.equal(view.selectedBorrowRecordId.value, 202)
|
||||
assert.deepEqual(lookups, ['A', 'B'])
|
||||
assert.deepEqual(submissions.map((row) => [row.equipment_code, row.borrow_record_id, row.return_condition]), [['B', 202, '损坏']])
|
||||
pendingWrite.resolve({ data: { need_confirm: false } })
|
||||
await write
|
||||
assert.match(view.pageNotice.value.message, /资产 B.*损坏/)
|
||||
})
|
||||
|
||||
test('leaving a prefilled return route for a blank scan invalidates the old lookup', async (t) => {
|
||||
const previous = deferred()
|
||||
const lookups = []
|
||||
const view = component(t, 'borrow/ReturnScan.vue', [
|
||||
'borrowRecordInfo', 'lookupLoading', 'selectedBorrowRecordId', 'canSubmit', 'pageNotice'
|
||||
], {
|
||||
getBorrowRecordByCode: (code) => { lookups.push(code); return previous.promise },
|
||||
getChildren: async () => ({ data: { children: [] } })
|
||||
})
|
||||
view.route.query = { equipmentCode: 'A', borrowRecordId: '101' }
|
||||
await nextTick()
|
||||
assert.deepEqual(lookups, ['A'])
|
||||
assert.equal(view.lookupLoading.value, true)
|
||||
view.route.query = {}
|
||||
await nextTick()
|
||||
previous.resolve(returnData('A', 1, 101))
|
||||
await turn()
|
||||
assert.equal(view.lookupLoading.value, false)
|
||||
assert.equal(view.borrowRecordInfo.value, null)
|
||||
assert.equal(view.selectedBorrowRecordId.value, null)
|
||||
assert.equal(view.canSubmit.value, false)
|
||||
assert.equal(view.pageNotice.value, null)
|
||||
})
|
||||
|
||||
test('inventory locks exception and scan actions until their writes and refresh settle', async (t) => {
|
||||
const pendingException = deferred()
|
||||
const pendingScan = deferred()
|
||||
const writes = []
|
||||
const codes = []
|
||||
const reads = []
|
||||
const task = { id: 1, status: 'active' }
|
||||
const actor = { task, participant: { id: 7 } }
|
||||
const assetA = { id: 11, equipment_code: 'A', equipment_name: '资产 A', check_status: 'pending' }
|
||||
const assetB = { id: 22, equipment_code: 'B', equipment_name: '资产 B', check_status: 'pending' }
|
||||
let failRefresh = false
|
||||
const view = component(t, 'inventory/PublicInventoryTask.vue', [
|
||||
'task', 'session', 'openExceptionModal', 'closeExceptionModal', 'submitException', 'exceptionTarget',
|
||||
'handleSubmitScan', 'handleCameraDetected', 'scanCode', 'feedback', 'actionLocked', 'lastHandledItem'
|
||||
], {
|
||||
submitPublicInventoryException: (id, payload, identity) => { writes.push({ id, payload, identity }); return pendingException.promise },
|
||||
submitPublicInventoryScan: (code, identity) => { codes.push({ code, identity }); return pendingScan.promise },
|
||||
getPublicInventoryTask: async () => {
|
||||
if (failRefresh) throw new Error('refresh unavailable')
|
||||
return { data: task }
|
||||
},
|
||||
getPublicInventoryMe: async (...args) => { reads.push(args); return { data: actor } },
|
||||
getPublicInventoryItems: async (...args) => { reads.push(args); return { data: { items: [assetA, assetB], summary: {} } } }
|
||||
})
|
||||
view.task.value = task
|
||||
view.session.value = actor
|
||||
view.openExceptionModal(assetA)
|
||||
const write = view.submitException()
|
||||
assert.equal(view.actionLocked.value, true)
|
||||
view.closeExceptionModal()
|
||||
view.openExceptionModal(assetB)
|
||||
await view.submitException()
|
||||
await view.handleCameraDetected('B')
|
||||
assert.equal(view.exceptionTarget.value.id, 11)
|
||||
const identity = { task_token: 'fixture-task', participant_id: 7 }
|
||||
assert.deepEqual(writes.map(({ id, identity }) => ({ id, identity })), [{ id: 11, identity }])
|
||||
assert.deepEqual(codes, [])
|
||||
pendingException.resolve({})
|
||||
await write
|
||||
assert.equal(view.exceptionTarget.value, null)
|
||||
assert.equal(view.lastHandledItem.value.id, 11)
|
||||
assert.match(view.feedback.value.text, /资产 A/)
|
||||
assert.deepEqual(reads, [['fixture-task', 7], ['fixture-task', 7]])
|
||||
view.scanCode.value = 'B'
|
||||
const scan = view.handleSubmitScan()
|
||||
await view.handleSubmitScan()
|
||||
await view.handleCameraDetected('C')
|
||||
view.openExceptionModal(assetA)
|
||||
assert.equal(view.exceptionTarget.value, null)
|
||||
assert.deepEqual(codes, [{ code: 'B', identity }])
|
||||
failRefresh = true
|
||||
pendingScan.resolve({ data: assetB })
|
||||
await scan
|
||||
assert.equal(view.feedback.value.type, 'info')
|
||||
assert.match(view.feedback.value.text, /已确认 资产 B.*未能刷新/)
|
||||
assert.equal(view.actionLocked.value, false)
|
||||
})
|
||||
|
||||
const sessionConflict = () => Object.assign(new Error('盘点会话已切换,请重新确认本页身份'), { status: 409 })
|
||||
|
||||
test('a write with another tab’s session clears only the local inventory and allows reconfirming this task', async (t) => {
|
||||
const task = { id: 1, status: 'active' }
|
||||
const actor = { task, participant: { id: 7 } }
|
||||
const asset = { id: 11, equipment_code: 'A', equipment_name: '资产 A' }
|
||||
const calls = []
|
||||
const view = component(t, 'inventory/PublicInventoryTask.vue', [
|
||||
'task', 'session', 'items', 'handleCameraDetected', 'identityNeedsConfirmation', 'feedback', 'selectedParticipantId', 'confirmIdentity'
|
||||
], {
|
||||
submitPublicInventoryScan: async (code, identity) => { calls.push(['scan', code, identity]); throw sessionConflict() },
|
||||
searchPublicInventoryParticipants: async (token) => { calls.push(['participants', token]); return { data: [actor.participant] } },
|
||||
confirmPublicInventoryParticipant: async (token, participantId) => {
|
||||
calls.push(['confirm', token, participantId])
|
||||
return { data: { participant_id: participantId } }
|
||||
},
|
||||
getPublicInventoryMe: async (...args) => { calls.push(['me', ...args]); return { data: actor } },
|
||||
getPublicInventoryItems: async (...args) => { calls.push(['items', ...args]); return { data: { items: [asset], summary: {} } } }
|
||||
})
|
||||
view.task.value = task
|
||||
view.session.value = actor
|
||||
view.items.value = [asset]
|
||||
await view.handleCameraDetected('A')
|
||||
await view.handleCameraDetected('A')
|
||||
assert.deepEqual(calls, [['scan', 'A', { task_token: 'fixture-task', participant_id: 7 }], ['participants', 'fixture-task']])
|
||||
assert.equal(view.session.value, null)
|
||||
assert.deepEqual(view.items.value, [])
|
||||
assert.equal(view.identityNeedsConfirmation.value, true)
|
||||
assert.match(view.feedback.value.text, /身份已变化.*重新确认/)
|
||||
view.selectedParticipantId.value = 7
|
||||
await view.confirmIdentity()
|
||||
assert.deepEqual(calls.slice(2), [['confirm', 'fixture-task', 7], ['me', 'fixture-task', 7], ['items', 'fixture-task', 7]])
|
||||
assert.equal(view.identityNeedsConfirmation.value, false)
|
||||
assert.equal(view.session.value.participant.id, 7)
|
||||
assert.equal(view.items.value[0].id, 11)
|
||||
})
|
||||
|
||||
test('initial inventory recovery binds the items request to the participant found by me', async (t) => {
|
||||
const task = { id: 1, status: 'active', identity_mode: 'dingtalk' }
|
||||
const actor = { task, participant: { id: 7 } }
|
||||
const calls = []
|
||||
const view = component(t, 'inventory/PublicInventoryTask.vue', [
|
||||
'bootstrap', 'confirmBoundIdentity', 'session', 'items', 'identityNeedsConfirmation', 'feedback'
|
||||
], {
|
||||
useAuthStore: () => ({ isAuthenticated: true, user: { person_id: 5 } }),
|
||||
getPublicInventoryTask: async () => ({ data: task }),
|
||||
getPublicInventoryMe: async (...args) => { calls.push(['me', ...args]); return { data: actor } },
|
||||
getPublicInventoryItems: async (...args) => {
|
||||
calls.push(['items', ...args])
|
||||
if (calls.length === 2) throw sessionConflict()
|
||||
return { data: { items: [{ id: 11 }], summary: {} } }
|
||||
},
|
||||
confirmCurrentInventoryParticipant: async (token) => {
|
||||
calls.push(['confirm', token])
|
||||
return { data: { participant_id: 7 } }
|
||||
}
|
||||
})
|
||||
await view.bootstrap()
|
||||
assert.deepEqual(calls, [['me', 'fixture-task', undefined], ['items', 'fixture-task', 7]])
|
||||
assert.equal(view.session.value, null)
|
||||
assert.deepEqual(view.items.value, [])
|
||||
assert.equal(view.identityNeedsConfirmation.value, true)
|
||||
assert.match(view.feedback.value.text, /身份已变化/)
|
||||
await view.confirmBoundIdentity()
|
||||
assert.deepEqual(calls.slice(2), [['confirm', 'fixture-task'], ['me', 'fixture-task', 7], ['items', 'fixture-task', 7]])
|
||||
assert.equal(view.session.value.participant.id, 7)
|
||||
assert.deepEqual(view.items.value, [{ id: 11 }])
|
||||
assert.equal(view.identityNeedsConfirmation.value, false)
|
||||
})
|
||||
@ -20,10 +20,12 @@ export interface DisposalRecord {
|
||||
completion_notes?: string
|
||||
pre_status?: string
|
||||
notes?: string
|
||||
requires_quantity_confirmation?: boolean
|
||||
equipment?: {
|
||||
equipment_name: string
|
||||
equipment_type: string
|
||||
unit_price: number
|
||||
total_quantity?: number
|
||||
}
|
||||
applier?: { id: number; name: string; username: string }
|
||||
approver?: { id: number; name: string; username: string }
|
||||
@ -43,11 +45,13 @@ export interface DisposalItem {
|
||||
pre_status?: string
|
||||
status_before?: string
|
||||
is_root?: boolean
|
||||
snapshot_json?: string | null
|
||||
equipment?: {
|
||||
id?: number
|
||||
equipment_code?: string
|
||||
equipment_name?: string
|
||||
equipment_type?: string
|
||||
total_quantity?: number
|
||||
}
|
||||
}
|
||||
|
||||
@ -121,7 +125,7 @@ export interface BatchDisposalCandidate {
|
||||
equipment_code: string
|
||||
equipment_name: string
|
||||
status: string
|
||||
items: Array<{ id: number; equipment_code: string; equipment_name: string }>
|
||||
items: Array<{ id: number; equipment_code: string; equipment_name: string; total_quantity?: number }>
|
||||
blocked_reason: string | null
|
||||
}
|
||||
|
||||
@ -131,7 +135,7 @@ export interface BatchDisposalPreview {
|
||||
}
|
||||
|
||||
export interface CreateBatchDisposalParams {
|
||||
assets: Array<{ equipment_id: number; item_ids: number[] }>
|
||||
assets: Array<{ equipment_id: number; item_ids: number[]; confirmed_quantities?: ConfirmedDisposalQuantity[] }>
|
||||
disposal_reason: string
|
||||
disposal_method: string
|
||||
notes?: string
|
||||
@ -170,7 +174,17 @@ export const getDisposalDetail = (id: number) => request
|
||||
.get<ApiResponse<DisposalRecord>>(`/disposal/${id}`)
|
||||
.then((response) => response.data)
|
||||
|
||||
export const approveDisposal = (id: number, data: { approved: boolean; reject_reason?: string }) =>
|
||||
export interface ConfirmedDisposalQuantity {
|
||||
equipment_id: number
|
||||
total_quantity: number
|
||||
}
|
||||
|
||||
export const approveDisposal = (id: number, data: {
|
||||
approved: boolean
|
||||
reject_reason?: string
|
||||
confirmed_quantities?: ConfirmedDisposalQuantity[]
|
||||
reconfirm_quantities?: boolean
|
||||
}) =>
|
||||
request.put(`/disposal/${id}/approve`, data)
|
||||
|
||||
export const completeDisposal = (id: number, data: { actual_value?: number; completion_notes?: string }) =>
|
||||
|
||||
@ -24,13 +24,18 @@ const publicInventoryApi = axios.create({
|
||||
}
|
||||
})
|
||||
|
||||
const SESSION_CHANGED_MESSAGE = '盘点会话已切换,请重新确认本页身份'
|
||||
|
||||
export const isPublicInventorySessionChanged = (error: unknown) =>
|
||||
error instanceof Error && (error as Error & { status?: number }).status === 409 && error.message === SESSION_CHANGED_MESSAGE
|
||||
|
||||
publicInventoryApi.interceptors.response.use(
|
||||
(response: AxiosResponse<ApiResponse>) => {
|
||||
const data = response.data as ApiResponse
|
||||
if (data?.code === 200) {
|
||||
return response
|
||||
}
|
||||
return Promise.reject(new Error(data?.message || '请求失败'))
|
||||
return Promise.reject(Object.assign(new Error(data?.message || '请求失败'), { status: data?.code }))
|
||||
},
|
||||
(error) => {
|
||||
const message =
|
||||
@ -38,7 +43,7 @@ publicInventoryApi.interceptors.response.use(
|
||||
error?.response?.data?.error ||
|
||||
error?.message ||
|
||||
'请求失败'
|
||||
return Promise.reject(new Error(message))
|
||||
return Promise.reject(Object.assign(new Error(message), { status: error?.response?.status }))
|
||||
}
|
||||
)
|
||||
|
||||
@ -87,19 +92,29 @@ export const confirmCurrentInventoryParticipant = async (token: string) => {
|
||||
return response.data
|
||||
}
|
||||
|
||||
export const getPublicInventoryMe = async () => {
|
||||
const response = await publicInventoryApi.get<ApiResponse<PublicInventorySessionData>>('/me')
|
||||
export const getPublicInventoryMe = async (taskToken: string, participantId?: number) => {
|
||||
const response = await publicInventoryApi.get<ApiResponse<PublicInventorySessionData>>('/me', {
|
||||
params: { task_token: taskToken, participant_id: participantId }
|
||||
})
|
||||
return response.data
|
||||
}
|
||||
|
||||
export const getPublicInventoryItems = async () => {
|
||||
const response = await publicInventoryApi.get<ApiResponse<PublicInventoryItemsResponse>>('/me/items')
|
||||
export const getPublicInventoryItems = async (taskToken: string, participantId: number) => {
|
||||
const response = await publicInventoryApi.get<ApiResponse<PublicInventoryItemsResponse>>('/me/items', {
|
||||
params: { task_token: taskToken, participant_id: participantId }
|
||||
})
|
||||
return response.data
|
||||
}
|
||||
|
||||
export const submitPublicInventoryScan = async (equipmentCode: string) => {
|
||||
interface PublicInventoryIdentity {
|
||||
task_token: string
|
||||
participant_id: number
|
||||
}
|
||||
|
||||
export const submitPublicInventoryScan = async (equipmentCode: string, identity: PublicInventoryIdentity) => {
|
||||
const response = await publicInventoryApi.post<ApiResponse<InventoryTaskItem>>('/me/scan', {
|
||||
equipment_code: equipmentCode
|
||||
equipment_code: equipmentCode,
|
||||
...identity
|
||||
})
|
||||
return response.data
|
||||
}
|
||||
@ -109,11 +124,12 @@ export const submitPublicInventoryException = async (
|
||||
data: {
|
||||
exception_type: 'not_found' | 'not_with_me'
|
||||
exception_note?: string
|
||||
}
|
||||
},
|
||||
identity: PublicInventoryIdentity
|
||||
) => {
|
||||
const response = await publicInventoryApi.post<ApiResponse<null>>(
|
||||
`/me/items/${itemId}/exception`,
|
||||
data
|
||||
{ ...data, ...identity }
|
||||
)
|
||||
return response.data
|
||||
}
|
||||
|
||||
@ -1,11 +1,20 @@
|
||||
<template>
|
||||
<div class="sheet-backdrop" @click.self="close">
|
||||
<form class="sheet-panel space-y-4" role="dialog" aria-modal="true" aria-labelledby="batch-disposal-title" @submit.prevent="submit" @keydown.esc.prevent="close">
|
||||
<dialog
|
||||
ref="dialogElement"
|
||||
class="sheet-backdrop batch-disposal-modal"
|
||||
aria-labelledby="batch-disposal-title"
|
||||
@click.self="close"
|
||||
@cancel.prevent="close"
|
||||
@keydown.tab="keepDialogTabFocus"
|
||||
>
|
||||
<form class="sheet-panel space-y-4" @submit.prevent="submit">
|
||||
<header>
|
||||
<h3 id="batch-disposal-title" class="section-title">{{ importMode ? '导入报废清单' : '批量报废' }}</h3>
|
||||
<p class="mt-2 text-sm text-text-secondary">预览并选择要申请的资产。提交后进入报废审批。</p>
|
||||
<h3 id="batch-disposal-title" ref="dialogTitle" class="section-title" tabindex="-1">{{ dialogHeading }}</h3>
|
||||
<p class="mt-2 text-sm text-text-secondary">{{ picking ? '搜索并勾选一项或多项资产,然后预检。' : '预览并选择要申请的资产。提交后进入报废审批。' }}</p>
|
||||
</header>
|
||||
|
||||
<DisposalAssetPicker v-if="props.pickAssets" v-show="picking" @cancel="close" @preview="previewSelection" />
|
||||
|
||||
<div v-if="importMode" class="field-stack">
|
||||
<input id="batch-disposal-file" ref="fileInput" type="file" accept=".xlsx,.xls,.csv" class="hidden" :disabled="busy" @change="handleFile">
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
@ -15,7 +24,7 @@
|
||||
<p class="text-sm text-text-secondary">支持 Excel、CSV,清单需包含“编码”“资产编码”或“设备编码”列。</p>
|
||||
</div>
|
||||
|
||||
<div v-if="loading || readingFile" class="panel text-sm text-text-secondary" role="status">正在读取并检查报废清单…</div>
|
||||
<div v-if="loading || readingFile" class="panel text-sm text-text-secondary" role="status">{{ importMode ? '正在读取并检查报废清单…' : '正在检查所选资产…' }}</div>
|
||||
<p v-if="errorMessage" class="text-sm text-status-error" role="alert">{{ errorMessage }}</p>
|
||||
|
||||
<section v-if="preview" class="space-y-4" aria-label="报废预览">
|
||||
@ -23,7 +32,10 @@
|
||||
<span class="badge badge-neutral">共 {{ preview.candidates.length }} 项</span>
|
||||
<span class="badge badge-success">可申请 {{ eligibleCandidates.length }} 项</span>
|
||||
<span class="badge badge-warning">不可申请 {{ preview.candidates.length - eligibleCandidates.length }} 项</span>
|
||||
<span class="badge badge-neutral">已选 {{ selectedCandidates.length }} 项</span>
|
||||
<span class="badge badge-neutral">已选 {{ selectedCandidates.length }} 项审批</span>
|
||||
<span v-if="selectedQuantity !== null && selectedCandidates.length" class="badge badge-neutral">
|
||||
含配件共 {{ selectedQuantity }} 件
|
||||
</span>
|
||||
</div>
|
||||
<p v-if="preview.duplicate_codes.length" class="break-words text-sm text-text-secondary">
|
||||
重复编码只计一次:{{ preview.duplicate_codes.join('、') }}
|
||||
@ -39,22 +51,33 @@
|
||||
<div class="flex flex-wrap items-start justify-between gap-2">
|
||||
<div class="min-w-0 flex-1 break-words">
|
||||
<p class="text-sm font-semibold text-text-primary">{{ candidate.equipment_name || candidate.equipment_code }}</p>
|
||||
<p v-if="candidate.equipment_name" class="mt-1 font-mono text-xs text-text-tertiary">{{ candidate.equipment_code }}</p>
|
||||
<p v-if="candidate.equipment_name" class="mt-1 font-mono text-xs text-text-tertiary">
|
||||
{{ candidate.equipment_code }}
|
||||
<span v-if="candidate.items[0]?.total_quantity !== undefined"> · {{ candidate.items[0].total_quantity }} 件</span>
|
||||
</p>
|
||||
</div>
|
||||
<span class="badge" :class="canApply(candidate) ? 'badge-neutral' : 'badge-warning'">{{ candidate.status || '不可申请' }}</span>
|
||||
</div>
|
||||
|
||||
<p v-if="!canApply(candidate)" class="text-sm text-status-warning">{{ candidate.blocked_reason || '该资产不可申请报废' }}</p>
|
||||
<details v-if="candidate.items.length > 1" class="text-sm text-text-secondary">
|
||||
<summary class="cursor-pointer text-text-primary">查看 {{ candidate.items.length - 1 }} 件配件</summary>
|
||||
<summary class="cursor-pointer text-text-primary">查看 {{ candidate.items.length - 1 }} 项配件</summary>
|
||||
<ul class="mt-2 space-y-1 pl-4">
|
||||
<li v-for="item in candidate.items.filter((item) => item.id !== candidate.equipment_id)" :key="item.id" class="break-words">
|
||||
<span class="font-mono text-xs">{{ item.equipment_code }}</span> {{ item.equipment_name }}
|
||||
<span v-if="item.total_quantity !== undefined"> · {{ item.total_quantity }} 件</span>
|
||||
</li>
|
||||
</ul>
|
||||
</details>
|
||||
<label v-if="canApply(candidate)" class="flex items-center gap-2 text-sm text-text-primary">
|
||||
<input v-model="selectedIds" type="checkbox" :value="candidate.equipment_id" :disabled="busy" class="rounded">
|
||||
<input
|
||||
v-model="selectedIds"
|
||||
type="checkbox"
|
||||
:value="candidate.equipment_id"
|
||||
:disabled="busy"
|
||||
:aria-label="candidate.items.length > 1 ? `确认整组申请 ${candidate.equipment_code} 及其配件` : `申请资产 ${candidate.equipment_code}`"
|
||||
class="rounded"
|
||||
>
|
||||
{{ candidate.items.length > 1 ? '确认整组申请(主资产及配件)' : '申请此资产' }}
|
||||
</label>
|
||||
</li>
|
||||
@ -81,19 +104,22 @@
|
||||
</div>
|
||||
</fieldset>
|
||||
|
||||
<footer class="flex flex-col-reverse gap-3 sm:flex-row sm:justify-end">
|
||||
<footer v-if="!picking" class="flex flex-col-reverse gap-3 sm:flex-row sm:justify-end">
|
||||
<button type="button" class="btn-secondary" :disabled="submitting" @click="close">取消</button>
|
||||
<button v-if="props.pickAssets" type="button" class="btn-secondary" :disabled="busy" @click="backToSelection">返回选资产</button>
|
||||
<button v-if="lastRequest && errorMessage" type="button" class="btn-secondary" :disabled="busy" @click="loadPreview(lastRequest)">重新预览</button>
|
||||
<button type="submit" class="btn-danger" :disabled="!canSubmit" :aria-busy="submitting">
|
||||
{{ submitting ? '正在提交…' : `提交 ${selectedCandidates.length} 项审批` }}
|
||||
</button>
|
||||
</footer>
|
||||
</form>
|
||||
</div>
|
||||
</dialog>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { computed, nextTick, onMounted, ref } from 'vue'
|
||||
import { keepDialogTabFocus } from '@/utils/dialogFocus'
|
||||
import DisposalAssetPicker from '@/components/DisposalAssetPicker.vue'
|
||||
import {
|
||||
createBatchDisposal,
|
||||
previewBatchDisposal,
|
||||
@ -101,12 +127,15 @@ import {
|
||||
type BatchDisposalPreview,
|
||||
type BatchDisposalPreviewParams
|
||||
} from '@/api/disposal'
|
||||
import { parseDisposalImport } from '@/utils/disposalImport'
|
||||
|
||||
const props = defineProps<{ equipmentIds: number[] }>()
|
||||
const props = defineProps<{ equipmentIds: number[]; pickAssets?: boolean }>()
|
||||
const emit = defineEmits<{ close: []; submitted: [result: { count: number; equipmentIds: number[] }] }>()
|
||||
|
||||
const importMode = props.equipmentIds.length === 0
|
||||
const importMode = !props.pickAssets && props.equipmentIds.length === 0
|
||||
const picking = ref(Boolean(props.pickAssets))
|
||||
const dialogHeading = computed(() => importMode ? '导入报废清单' : picking.value ? '选择报废资产' : '批量报废')
|
||||
const dialogElement = ref<HTMLDialogElement | null>(null)
|
||||
const dialogTitle = ref<HTMLElement | null>(null)
|
||||
const preview = ref<BatchDisposalPreview | null>(null)
|
||||
const lastRequest = ref<BatchDisposalPreviewParams | null>(null)
|
||||
const fileInput = ref<HTMLInputElement | null>(null)
|
||||
@ -132,7 +161,13 @@ const selectedCandidates = computed(() => {
|
||||
.filter((candidate) => selected.has(candidate.equipment_id))
|
||||
.map((candidate) => [candidate.equipment_id, candidate])).values())
|
||||
})
|
||||
const canSubmit = computed(() => !busy.value && selectedCandidates.value.length > 0 && Boolean(reason.value.trim()))
|
||||
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 selectStandalone = () => {
|
||||
selectedIds.value = Array.from(new Set([
|
||||
@ -142,7 +177,9 @@ const selectStandalone = () => {
|
||||
}
|
||||
|
||||
const close = () => {
|
||||
if (!submitting.value) emit('close')
|
||||
if (submitting.value) return
|
||||
dialogElement.value?.close()
|
||||
emit('close')
|
||||
}
|
||||
|
||||
const loadPreview = async (params: BatchDisposalPreviewParams) => {
|
||||
@ -164,6 +201,23 @@ const loadPreview = async (params: BatchDisposalPreviewParams) => {
|
||||
}
|
||||
}
|
||||
|
||||
const previewSelection = (equipmentIds: number[]) => {
|
||||
if (!picking.value || !equipmentIds.length) return
|
||||
picking.value = false
|
||||
void nextTick(() => dialogTitle.value?.focus({ preventScroll: true }))
|
||||
void loadPreview({ equipment_ids: equipmentIds })
|
||||
}
|
||||
|
||||
const backToSelection = () => {
|
||||
if (busy.value) return
|
||||
preview.value = null
|
||||
lastRequest.value = null
|
||||
selectedIds.value = []
|
||||
errorMessage.value = ''
|
||||
picking.value = true
|
||||
void nextTick(() => dialogTitle.value?.focus({ preventScroll: true }))
|
||||
}
|
||||
|
||||
const handleFile = async (event: Event) => {
|
||||
const input = event.target as HTMLInputElement
|
||||
const file = input.files?.[0]
|
||||
@ -177,7 +231,10 @@ const handleFile = async (event: Event) => {
|
||||
errorMessage.value = ''
|
||||
readingFile.value = true
|
||||
try {
|
||||
const source = /\.csv$/i.test(file.name) ? await file.text() : await file.arrayBuffer()
|
||||
const [{ parseDisposalImport }, source] = await Promise.all([
|
||||
import('@/utils/disposalImport'),
|
||||
/\.csv$/i.test(file.name) ? file.text() : file.arrayBuffer()
|
||||
])
|
||||
const codes = parseDisposalImport(source)
|
||||
if (!codes.length) throw new Error('清单中没有可读取的资产编码,请检查编码列和数据')
|
||||
await loadPreview({ equipment_codes: codes })
|
||||
@ -190,10 +247,17 @@ const handleFile = async (event: Event) => {
|
||||
|
||||
const submit = async () => {
|
||||
if (!canSubmit.value) return
|
||||
const assets = selectedCandidates.value.map((candidate) => ({
|
||||
equipment_id: candidate.equipment_id,
|
||||
item_ids: candidate.items.map((item) => item.id)
|
||||
}))
|
||||
const assets = selectedCandidates.value.map((candidate) => {
|
||||
const quantities = candidate.items.flatMap((item) => item.total_quantity === undefined ? [] : [{
|
||||
equipment_id: item.id,
|
||||
total_quantity: item.total_quantity
|
||||
}])
|
||||
return {
|
||||
equipment_id: candidate.equipment_id,
|
||||
item_ids: candidate.items.map((item) => item.id),
|
||||
confirmed_quantities: quantities.length === candidate.items.length ? quantities : undefined
|
||||
}
|
||||
})
|
||||
submitting.value = true
|
||||
errorMessage.value = ''
|
||||
try {
|
||||
@ -204,6 +268,7 @@ const submit = async () => {
|
||||
notes: notes.value.trim() || undefined
|
||||
})
|
||||
if (!response.data) throw new Error('未收到审批结果,请核对报废记录')
|
||||
dialogElement.value?.close()
|
||||
emit('submitted', { count: response.data.count, equipmentIds: assets.flatMap((asset) => asset.item_ids) })
|
||||
} catch (error) {
|
||||
errorMessage.value = error instanceof Error ? error.message : '提交失败,请重试'
|
||||
@ -213,6 +278,27 @@ const submit = async () => {
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
if (!importMode) void loadPreview({ equipment_ids: props.equipmentIds })
|
||||
dialogElement.value?.showModal()
|
||||
dialogTitle.value?.focus({ preventScroll: true })
|
||||
if (!importMode && !picking.value) void loadPreview({ equipment_ids: props.equipmentIds })
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.batch-disposal-modal {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
max-width: none;
|
||||
max-height: none;
|
||||
margin: 0;
|
||||
color: inherit;
|
||||
}
|
||||
|
||||
.batch-disposal-modal:not([open]) {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.batch-disposal-modal::backdrop {
|
||||
background: transparent;
|
||||
}
|
||||
</style>
|
||||
|
||||
130
frontend/src/components/DisposalAssetPicker.vue
Normal file
130
frontend/src/components/DisposalAssetPicker.vue
Normal file
@ -0,0 +1,130 @@
|
||||
<template>
|
||||
<section class="space-y-4" aria-label="选择报废资产">
|
||||
<div class="field-stack">
|
||||
<label for="disposal-asset-keyword" class="field-label">资产编码或名称</label>
|
||||
<div class="flex flex-col gap-2 sm:flex-row">
|
||||
<input
|
||||
id="disposal-asset-keyword"
|
||||
v-model.trim="keyword"
|
||||
type="search"
|
||||
class="input min-w-0 flex-1"
|
||||
placeholder="输入资产编码或名称"
|
||||
@keydown.enter.prevent="search"
|
||||
>
|
||||
<button type="button" class="btn-secondary" @click="search">搜索</button>
|
||||
</div>
|
||||
<p class="text-sm text-text-secondary">可以跨搜索和分页勾选。已挂载的配件随主资产在预检时核对。</p>
|
||||
</div>
|
||||
|
||||
<div v-if="loading" class="panel text-sm text-text-secondary" role="status">正在搜索资产…</div>
|
||||
<p v-else-if="errorMessage" class="text-sm text-status-error" role="alert">{{ errorMessage }}</p>
|
||||
<template v-else>
|
||||
<ul v-if="results.length" class="max-h-72 space-y-2 overflow-y-auto" aria-label="资产搜索结果" tabindex="0">
|
||||
<li v-for="asset in results" :key="asset.id">
|
||||
<label class="panel flex cursor-pointer items-center gap-3">
|
||||
<input
|
||||
type="checkbox"
|
||||
class="shrink-0 rounded"
|
||||
:checked="selected.has(asset.id)"
|
||||
:aria-label="`选择资产 ${asset.equipment_code} ${asset.equipment_name}`"
|
||||
@change="toggleAsset(asset)"
|
||||
>
|
||||
<span class="min-w-0 flex-1 break-words">
|
||||
<span class="block text-sm font-medium text-text-primary">{{ asset.equipment_name }}</span>
|
||||
<span class="block font-mono text-xs text-text-secondary">{{ asset.equipment_code }}</span>
|
||||
<span v-if="matchingAccessories(asset).length" class="block text-xs text-text-secondary">
|
||||
匹配配件:{{ matchingAccessories(asset).join('、') }}
|
||||
</span>
|
||||
</span>
|
||||
<span v-if="asset.status" class="badge badge-neutral shrink-0">{{ asset.status }}</span>
|
||||
</label>
|
||||
</li>
|
||||
</ul>
|
||||
<p v-else class="panel text-sm text-text-secondary">没有找到匹配的资产,试试其他编码或名称。</p>
|
||||
<div v-if="pageCount > 1" class="flex flex-wrap items-center justify-between gap-2">
|
||||
<span class="text-sm text-text-secondary">第 {{ page }} / {{ pageCount }} 页,共 {{ total }} 项</span>
|
||||
<div class="flex gap-2">
|
||||
<button type="button" class="btn-secondary text-sm" :disabled="page <= 1" @click="changePage(page - 1)">上一页</button>
|
||||
<button type="button" class="btn-secondary text-sm" :disabled="page >= pageCount" @click="changePage(page + 1)">下一页</button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<details v-if="selected.size" class="panel text-sm">
|
||||
<summary class="cursor-pointer text-text-primary">已选 {{ selected.size }} 项资产</summary>
|
||||
<ul class="mt-2 max-h-40 space-y-2 overflow-y-auto">
|
||||
<li v-for="asset in selected.values()" :key="asset.id" class="flex items-center justify-between gap-2">
|
||||
<span class="min-w-0 break-words text-text-secondary">{{ asset.equipment_code }} · {{ asset.equipment_name }}</span>
|
||||
<button type="button" class="btn-secondary shrink-0 text-sm" :aria-label="`移除资产 ${asset.equipment_code}`" @click="selected.delete(asset.id)">移除</button>
|
||||
</li>
|
||||
</ul>
|
||||
</details>
|
||||
|
||||
<footer class="flex flex-col-reverse gap-2 sm:flex-row sm:justify-end">
|
||||
<button type="button" class="btn-secondary" @click="emit('cancel')">取消</button>
|
||||
<button type="button" class="btn-primary" :disabled="!selected.size" @click="emit('preview', [...selected.keys()])">
|
||||
预检已选资产{{ selected.size ? `(${selected.size} 项)` : '' }}
|
||||
</button>
|
||||
</footer>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
|
||||
import { getEquipmentList } from '@/api/equipment'
|
||||
import type { Equipment } from '@/types'
|
||||
import { createRequestScope } from '@/utils/requestScope'
|
||||
|
||||
const emit = defineEmits<{ cancel: []; preview: [equipmentIds: number[]] }>()
|
||||
const requestScope = createRequestScope()
|
||||
const pageSize = 20
|
||||
const keyword = ref('')
|
||||
const appliedKeyword = ref('')
|
||||
const results = ref<Equipment[]>([])
|
||||
const selected = ref(new Map<number, Pick<Equipment, 'id' | 'equipment_code' | 'equipment_name'>>())
|
||||
const page = ref(1)
|
||||
const total = ref(0)
|
||||
const loading = ref(false)
|
||||
const errorMessage = ref('')
|
||||
const pageCount = computed(() => Math.max(1, Math.ceil(total.value / pageSize)))
|
||||
|
||||
const load = async (targetPage: number, searchKeyword: string) => {
|
||||
const request = requestScope.begin()
|
||||
loading.value = true
|
||||
errorMessage.value = ''
|
||||
try {
|
||||
const response = await getEquipmentList({ page: targetPage, pageSize, keyword: searchKeyword || undefined })
|
||||
if (!requestScope.isCurrent(request)) return
|
||||
if (!response.data) throw new Error('没有读取到资产搜索结果')
|
||||
results.value = response.data.list
|
||||
total.value = response.data.total
|
||||
page.value = targetPage
|
||||
appliedKeyword.value = searchKeyword
|
||||
} catch (error) {
|
||||
if (requestScope.isCurrent(request)) errorMessage.value = error instanceof Error ? error.message : '资产搜索失败,请重新搜索'
|
||||
} finally {
|
||||
if (requestScope.isCurrent(request)) loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const search = () => load(1, keyword.value.trim())
|
||||
const changePage = (targetPage: number) => {
|
||||
if (!loading.value && targetPage >= 1 && targetPage <= pageCount.value) void load(targetPage, appliedKeyword.value)
|
||||
}
|
||||
|
||||
const matchingAccessories = (asset: Equipment) => {
|
||||
const term = appliedKeyword.value.toLowerCase()
|
||||
if (!term) return []
|
||||
return (asset.children || [])
|
||||
.filter((child) => child.equipment_code.toLowerCase().includes(term) || child.equipment_name.toLowerCase().includes(term))
|
||||
.map((child) => child.equipment_code)
|
||||
}
|
||||
|
||||
const toggleAsset = ({ id, equipment_code, equipment_name }: Equipment) => {
|
||||
if (selected.value.has(id)) selected.value.delete(id)
|
||||
else selected.value.set(id, { id, equipment_code, equipment_name })
|
||||
}
|
||||
|
||||
onMounted(search)
|
||||
onBeforeUnmount(requestScope.dispose)
|
||||
</script>
|
||||
@ -1,17 +1,17 @@
|
||||
<template>
|
||||
<div class="min-h-screen bg-bg-primary">
|
||||
<div class="flex min-h-screen">
|
||||
<!-- 移动端遮罩 -->
|
||||
<div
|
||||
v-if="mobileNavOpen"
|
||||
class="fixed inset-0 z-40 bg-black/60 backdrop-blur-sm lg:hidden"
|
||||
@click="mobileNavOpen = false"
|
||||
></div>
|
||||
|
||||
<!-- 侧边栏 -->
|
||||
<aside
|
||||
class="fixed inset-y-0 left-0 z-50 flex w-64 max-w-[80vw] flex-col border-r border-border bg-bg-secondary transition-transform duration-200 lg:w-56 lg:max-w-none lg:translate-x-0"
|
||||
:class="mobileNavOpen ? 'translate-x-0' : '-translate-x-full'"
|
||||
<component
|
||||
:is="mobileViewport ? 'dialog' : 'aside'"
|
||||
id="app-navigation"
|
||||
ref="navigationPanel"
|
||||
class="fixed inset-y-0 left-0 z-50 flex w-64 max-w-[80vw] flex-col border-r border-border bg-bg-secondary lg:w-56 lg:max-w-none"
|
||||
:class="{ 'mobile-navigation': mobileViewport }"
|
||||
:aria-labelledby="mobileViewport ? 'app-site-name' : undefined"
|
||||
@cancel.prevent="closeMobileNav"
|
||||
@click.self="closeNavFromBackdrop"
|
||||
@keydown.tab="keepDialogTabFocus"
|
||||
>
|
||||
<!-- Logo 区域 -->
|
||||
<div class="flex items-center justify-between border-b border-border p-3 lg:block">
|
||||
@ -21,24 +21,24 @@
|
||||
<span v-else class="text-sm font-bold text-white">资</span>
|
||||
</div>
|
||||
<div class="min-w-0 flex-1">
|
||||
<h1 class="truncate text-sm font-semibold text-text-primary">{{ siteStore.siteName }}</h1>
|
||||
<h1 id="app-site-name" class="truncate text-sm font-semibold text-text-primary">{{ siteStore.siteName }}</h1>
|
||||
<p class="text-xs text-text-tertiary">固定资产</p>
|
||||
</div>
|
||||
</div>
|
||||
<button type="button" class="btn-icon lg:hidden" @click="mobileNavOpen = false" aria-label="关闭导航">
|
||||
<button type="button" class="btn-icon lg:hidden" @click="closeMobileNav" aria-label="关闭导航">
|
||||
<XMarkIcon class="h-5 w-5" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- 导航菜单 -->
|
||||
<nav class="flex-1 space-y-0.5 overflow-y-auto p-2">
|
||||
<nav class="flex-1 space-y-0.5 overflow-y-auto p-2" aria-label="主导航">
|
||||
<router-link
|
||||
v-for="item in visibleNavItems"
|
||||
:key="item.path"
|
||||
:to="item.path"
|
||||
class="nav-link"
|
||||
:class="{ active: isActive(item.path) }"
|
||||
@click="mobileNavOpen = false"
|
||||
@click="closeMobileNav"
|
||||
>
|
||||
<component :is="item.icon" class="h-5 w-5" />
|
||||
<span>{{ item.title }}</span>
|
||||
@ -66,7 +66,7 @@
|
||||
v-if="authStore.can(PERMISSIONS.SYSTEM_SETTINGS)"
|
||||
type="button"
|
||||
class="btn-secondary min-h-[34px] px-2.5 text-xs"
|
||||
@click="router.push('/settings')"
|
||||
@click="openSettings"
|
||||
>
|
||||
设置
|
||||
</button>
|
||||
@ -79,7 +79,7 @@
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</aside>
|
||||
</component>
|
||||
|
||||
<!-- 主内容区 -->
|
||||
<main class="flex min-w-0 flex-1 flex-col lg:ml-56">
|
||||
@ -87,7 +87,14 @@
|
||||
<header class="sticky top-0 z-30 border-b border-border bg-bg-secondary/95 backdrop-blur">
|
||||
<div class="flex items-center justify-between gap-4 px-3 py-3 sm:px-4">
|
||||
<div class="flex min-w-0 items-center gap-2.5">
|
||||
<button type="button" class="btn-icon lg:hidden" @click="mobileNavOpen = true" aria-label="打开导航">
|
||||
<button
|
||||
type="button"
|
||||
class="btn-icon lg:hidden"
|
||||
aria-label="打开导航"
|
||||
aria-controls="app-navigation"
|
||||
:aria-expanded="mobileNavOpen"
|
||||
@click="openMobileNav"
|
||||
>
|
||||
<Bars3Icon class="h-5 w-5" />
|
||||
</button>
|
||||
<div class="min-w-0">
|
||||
@ -129,7 +136,7 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
import { useNotificationStore } from '@/stores/notifications'
|
||||
@ -149,13 +156,49 @@ import {
|
||||
UserCircleIcon
|
||||
} from '@heroicons/vue/24/outline'
|
||||
import { getRoleLabel, PERMISSIONS } from '@/auth/permissions'
|
||||
import { keepDialogTabFocus } from '@/utils/dialogFocus'
|
||||
|
||||
const router = useRouter()
|
||||
const route = useRoute()
|
||||
const authStore = useAuthStore()
|
||||
const notificationStore = useNotificationStore()
|
||||
const siteStore = useSiteStore()
|
||||
const desktopViewport = window.matchMedia('(min-width: 1024px)')
|
||||
const mobileViewport = ref(!desktopViewport.matches)
|
||||
const mobileNavOpen = ref(false)
|
||||
const navigationPanel = ref<HTMLElement | null>(null)
|
||||
|
||||
const openMobileNav = () => {
|
||||
const dialog = navigationPanel.value
|
||||
if (!(dialog instanceof HTMLDialogElement) || dialog.open) return
|
||||
dialog.showModal()
|
||||
mobileNavOpen.value = true
|
||||
}
|
||||
|
||||
const closeMobileNav = () => {
|
||||
const dialog = navigationPanel.value
|
||||
if (dialog instanceof HTMLDialogElement && dialog.open) dialog.close()
|
||||
mobileNavOpen.value = false
|
||||
}
|
||||
|
||||
const closeNavFromBackdrop = (event: MouseEvent) => {
|
||||
const dialog = navigationPanel.value
|
||||
if (!(dialog instanceof HTMLDialogElement) || !dialog.open) return
|
||||
const { left, right, top, bottom } = dialog.getBoundingClientRect()
|
||||
if (event.clientX < left || event.clientX > right || event.clientY < top || event.clientY > bottom) {
|
||||
closeMobileNav()
|
||||
}
|
||||
}
|
||||
|
||||
const syncViewport = () => {
|
||||
if (desktopViewport.matches) closeMobileNav()
|
||||
mobileViewport.value = !desktopViewport.matches
|
||||
}
|
||||
|
||||
const openSettings = () => {
|
||||
closeMobileNav()
|
||||
void router.push('/settings')
|
||||
}
|
||||
|
||||
const navItems = [
|
||||
{ path: '/dashboard', title: '首页', icon: HomeIcon },
|
||||
@ -218,12 +261,7 @@ const handleLogout = async () => {
|
||||
router.push('/login')
|
||||
}
|
||||
|
||||
watch(
|
||||
() => route.fullPath,
|
||||
() => {
|
||||
mobileNavOpen.value = false
|
||||
}
|
||||
)
|
||||
watch(() => route.fullPath, closeMobileNav)
|
||||
|
||||
watch(
|
||||
() => authStore.user?.permissions,
|
||||
@ -236,6 +274,32 @@ watch(
|
||||
)
|
||||
|
||||
onMounted(() => {
|
||||
desktopViewport.addEventListener('change', syncViewport)
|
||||
syncViewport()
|
||||
siteStore.fetchSiteConfig()
|
||||
})
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
desktopViewport.removeEventListener('change', syncViewport)
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.mobile-navigation {
|
||||
inset: 0 auto 0 0;
|
||||
height: 100%;
|
||||
max-height: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
color: inherit;
|
||||
}
|
||||
|
||||
.mobile-navigation:not([open]) {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.mobile-navigation::backdrop {
|
||||
background: rgb(0 0 0 / 60%);
|
||||
backdrop-filter: blur(4px);
|
||||
}
|
||||
</style>
|
||||
|
||||
@ -12,7 +12,7 @@
|
||||
|
||||
--text-primary: #ffffff;
|
||||
--text-secondary: #a1a1a1;
|
||||
--text-tertiary: #6e6e6e;
|
||||
--text-tertiary: #949494;
|
||||
|
||||
--border-color: #2a2a2a;
|
||||
--border-hover: #3a3a3a;
|
||||
|
||||
8
frontend/src/utils/assetCharts.ts
Normal file
8
frontend/src/utils/assetCharts.ts
Normal file
@ -0,0 +1,8 @@
|
||||
import { BarChart, PieChart } from 'echarts/charts'
|
||||
import { GridComponent, LegendComponent, TooltipComponent } from 'echarts/components'
|
||||
import { init, use } from 'echarts/core'
|
||||
import { CanvasRenderer } from 'echarts/renderers'
|
||||
|
||||
use([BarChart, PieChart, GridComponent, LegendComponent, TooltipComponent, CanvasRenderer])
|
||||
|
||||
export { init }
|
||||
20
frontend/src/utils/dialogFocus.ts
Normal file
20
frontend/src/utils/dialogFocus.ts
Normal file
@ -0,0 +1,20 @@
|
||||
export const keepDialogTabFocus = (event: KeyboardEvent) => {
|
||||
const dialog = event.currentTarget
|
||||
if (!(dialog instanceof HTMLDialogElement) || !dialog.open) return
|
||||
|
||||
const tabStops = Array.from(dialog.querySelectorAll<HTMLElement>('a[href], button, input, select, textarea, summary, [tabindex]'))
|
||||
.filter(element => element.tabIndex >= 0 && !element.matches(':disabled') &&
|
||||
element.getClientRects().length > 0 && getComputedStyle(element).visibility === 'visible')
|
||||
const first = tabStops[0]
|
||||
const last = tabStops[tabStops.length - 1]
|
||||
if (!first || !last) return
|
||||
|
||||
const active = dialog.ownerDocument.activeElement
|
||||
if (event.shiftKey && (active === first || (active instanceof HTMLElement && !tabStops.includes(active)))) {
|
||||
event.preventDefault()
|
||||
last.focus()
|
||||
} else if (!event.shiftKey && active === last) {
|
||||
event.preventDefault()
|
||||
first.focus()
|
||||
}
|
||||
}
|
||||
@ -17,8 +17,9 @@
|
||||
<div class="px-5 py-5">
|
||||
<form v-if="isLocalAuth" @submit.prevent="handleLocalLogin" class="space-y-4">
|
||||
<div class="field-stack">
|
||||
<label class="field-label">用户名</label>
|
||||
<label for="login-username" class="field-label">用户名</label>
|
||||
<input
|
||||
id="login-username"
|
||||
v-model.trim="username"
|
||||
type="text"
|
||||
class="input"
|
||||
@ -28,8 +29,9 @@
|
||||
</div>
|
||||
|
||||
<div class="field-stack">
|
||||
<label class="field-label">密码</label>
|
||||
<label for="login-password" class="field-label">密码</label>
|
||||
<input
|
||||
id="login-password"
|
||||
v-model="password"
|
||||
type="password"
|
||||
class="input"
|
||||
@ -38,7 +40,7 @@
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div v-if="errorText" class="rounded-xl border border-status-error/30 bg-status-error/10 px-3 py-2 text-sm text-status-error">
|
||||
<div v-if="errorText" role="alert" class="rounded-xl border border-status-error/30 bg-status-error/10 px-3 py-2 text-sm text-status-error">
|
||||
{{ errorText }}
|
||||
</div>
|
||||
|
||||
@ -50,7 +52,7 @@
|
||||
{{ loading ? '登录中...' : '进入系统' }}
|
||||
</button>
|
||||
|
||||
<template v-if="dingtalkAvailable">
|
||||
<template v-if="dingtalkConfig === 'available'">
|
||||
<div class="flex items-center gap-3 py-1" aria-hidden="true">
|
||||
<span class="h-px flex-1 bg-border"></span>
|
||||
<span class="text-xs text-text-tertiary">或</span>
|
||||
@ -58,6 +60,7 @@
|
||||
</div>
|
||||
|
||||
<button
|
||||
ref="dingtalkLoginButton"
|
||||
type="button"
|
||||
class="btn-secondary w-full justify-center"
|
||||
:disabled="loading"
|
||||
@ -69,6 +72,20 @@
|
||||
在职员工无需单独申请普通账号,管理员、行政和 IT 仍按系统角色授权。
|
||||
</p>
|
||||
</template>
|
||||
<div v-else-if="dingtalkConfig === 'error'" class="panel flex flex-wrap items-center justify-between gap-3">
|
||||
<p role="status" class="text-sm text-text-secondary">
|
||||
{{ loadingDingtalkConfig ? '正在加载钉钉登录入口…' : '暂时无法加载钉钉登录入口。' }}
|
||||
</p>
|
||||
<button
|
||||
ref="retryDingtalkButton"
|
||||
type="button"
|
||||
class="btn-secondary text-sm"
|
||||
:aria-disabled="loadingDingtalkConfig"
|
||||
@click="loadDingTalkConfig"
|
||||
>
|
||||
重试加载
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<div v-else class="space-y-4">
|
||||
@ -98,7 +115,7 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { computed, nextTick, onMounted, ref } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
import keycloak from '@/auth/keycloak'
|
||||
@ -113,7 +130,10 @@ const loading = ref(false)
|
||||
const username = ref('')
|
||||
const password = ref('')
|
||||
const errorText = ref('')
|
||||
const dingtalkAvailable = ref(false)
|
||||
const dingtalkConfig = ref<'available' | 'unconfigured' | 'error'>('unconfigured')
|
||||
const loadingDingtalkConfig = ref(false)
|
||||
const dingtalkLoginButton = ref<HTMLButtonElement | null>(null)
|
||||
const retryDingtalkButton = ref<HTMLButtonElement | null>(null)
|
||||
const siteStore = useSiteStore()
|
||||
|
||||
const authMode = resolveAuthMode((import.meta.env as any).VITE_AUTH_MODE)
|
||||
@ -134,7 +154,7 @@ const handleLogin = async () => {
|
||||
const canSubmit = computed(() => username.value.length > 0 && password.value.length > 0)
|
||||
|
||||
const handleLocalLogin = async () => {
|
||||
if (!canSubmit.value) return
|
||||
if (loading.value || !canSubmit.value) return
|
||||
loading.value = true
|
||||
errorText.value = ''
|
||||
try {
|
||||
@ -166,15 +186,28 @@ const handleDingTalkLogin = async () => {
|
||||
})
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
siteStore.fetchSiteConfig()
|
||||
if (!isLocalAuth.value) return
|
||||
|
||||
const loadDingTalkConfig = async () => {
|
||||
if (loadingDingtalkConfig.value) return
|
||||
loadingDingtalkConfig.value = true
|
||||
try {
|
||||
const response = await getDingTalkPublicConfig('/dashboard')
|
||||
dingtalkAvailable.value = Boolean(response.data?.configured && response.data?.loginEntryUrl)
|
||||
const restoreFocus = document.activeElement === retryDingtalkButton.value
|
||||
dingtalkConfig.value = response.data?.configured && response.data?.loginEntryUrl
|
||||
? 'available'
|
||||
: 'unconfigured'
|
||||
if (restoreFocus && dingtalkConfig.value === 'available') {
|
||||
await nextTick()
|
||||
dingtalkLoginButton.value?.focus()
|
||||
}
|
||||
} catch {
|
||||
dingtalkAvailable.value = false
|
||||
dingtalkConfig.value = 'error'
|
||||
} finally {
|
||||
loadingDingtalkConfig.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
siteStore.fetchSiteConfig()
|
||||
if (isLocalAuth.value) void loadDingTalkConfig()
|
||||
})
|
||||
</script>
|
||||
|
||||
@ -8,7 +8,7 @@
|
||||
<div class="mt-3 flex flex-wrap gap-2">
|
||||
<router-link to="/borrow/scan" class="btn-primary text-sm">扫码出库</router-link>
|
||||
<router-link to="/return/scan" class="btn-secondary text-sm">扫码入库</router-link>
|
||||
<button class="btn-secondary text-sm" :disabled="exporting || !appliedFilters" @click="handleExport">
|
||||
<button class="btn-secondary text-sm" :disabled="loading || exporting || !appliedFilters" @click="handleExport">
|
||||
{{ exporting ? '导出中...' : '导出' }}
|
||||
</button>
|
||||
</div>
|
||||
@ -34,9 +34,9 @@
|
||||
|
||||
<!-- 筛选区域 -->
|
||||
<section class="card">
|
||||
<div class="filter-bar">
|
||||
<form class="filter-bar" aria-label="查询借用记录" @submit.prevent="handleSearch">
|
||||
<div class="filter-bar__inputs">
|
||||
<select v-model="filters.status" class="select" @change="handleSearch">
|
||||
<select v-model="filters.status" aria-label="借用状态" class="select" @change="handleSearch">
|
||||
<option value="">全部状态</option>
|
||||
<option value="已借出">已借出</option>
|
||||
<option value="已归还">已归还</option>
|
||||
@ -46,19 +46,26 @@
|
||||
v-model.trim="filters.person_name"
|
||||
class="input"
|
||||
type="text"
|
||||
aria-label="使用者"
|
||||
placeholder="输入花名、姓名或工号"
|
||||
@keyup.enter="handleSearch"
|
||||
/>
|
||||
<input
|
||||
v-model.trim="filters.keyword"
|
||||
class="input"
|
||||
type="text"
|
||||
aria-label="资产名称或编码"
|
||||
placeholder="资产名称/编码"
|
||||
@keyup.enter="handleSearch"
|
||||
/>
|
||||
<button class="btn-secondary text-xs sm:text-sm" @click="handleReset">重置</button>
|
||||
<div class="flex gap-2">
|
||||
<button type="submit" class="btn-primary text-sm" :disabled="loading">
|
||||
{{ loading ? '查询中…' : '查询' }}
|
||||
</button>
|
||||
<button type="button" class="btn-secondary text-sm" @click="handleReset">重置</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
<p v-if="listError" class="mt-3 text-sm text-status-error" role="alert">{{ listError }}</p>
|
||||
<p v-if="exportError" class="mt-3 text-sm text-status-error" role="alert">{{ exportError }}</p>
|
||||
</section>
|
||||
|
||||
<!-- 数据列表 -->
|
||||
@ -109,7 +116,7 @@
|
||||
</div>
|
||||
</div>
|
||||
</article>
|
||||
<p v-if="!loading && borrowRecords.length === 0" class="text-center text-sm text-text-tertiary py-8">
|
||||
<p v-if="!loading && !listError && borrowRecords.length === 0" class="text-center text-sm text-text-tertiary py-8">
|
||||
当前筛选条件下暂无记录。
|
||||
</p>
|
||||
</div>
|
||||
@ -161,7 +168,7 @@
|
||||
</span>
|
||||
</td>
|
||||
</tr>
|
||||
<tr v-if="!loading && borrowRecords.length === 0">
|
||||
<tr v-if="!loading && !listError && borrowRecords.length === 0">
|
||||
<td colspan="7" class="text-center text-text-secondary py-8">当前筛选条件下暂无记录。</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
@ -225,6 +232,8 @@ type BorrowFilters = Pick<Parameters<typeof getBorrowRecordList>[0], 'status' |
|
||||
const borrowRecords = ref<BorrowRecord[]>([])
|
||||
const loading = ref(false)
|
||||
const exporting = ref(false)
|
||||
const listError = ref('')
|
||||
const exportError = ref('')
|
||||
const total = ref(0)
|
||||
const currentPage = ref(1)
|
||||
const pageSize = ref(20)
|
||||
@ -249,20 +258,25 @@ const pageSummary = computed(() => {
|
||||
const fetchData = async (page: number, requestFilters: BorrowFilters = appliedFilters.value ?? {}) => {
|
||||
const request = listRequests.begin()
|
||||
loading.value = true
|
||||
listError.value = ''
|
||||
try {
|
||||
const res = await getBorrowRecordList({
|
||||
page,
|
||||
pageSize: pageSize.value,
|
||||
...requestFilters
|
||||
})
|
||||
if (listRequests.isCurrent(request) && res.data) {
|
||||
borrowRecords.value = res.data.list
|
||||
total.value = res.data.total
|
||||
currentPage.value = page
|
||||
appliedFilters.value = requestFilters
|
||||
if (!listRequests.isCurrent(request)) return
|
||||
if (!res.data) throw new Error('借用记录响应为空')
|
||||
borrowRecords.value = res.data.list
|
||||
total.value = res.data.total
|
||||
currentPage.value = page
|
||||
appliedFilters.value = requestFilters
|
||||
} catch {
|
||||
if (listRequests.isCurrent(request)) {
|
||||
listError.value = appliedFilters.value
|
||||
? '查询失败,仍显示上次查询结果。请重试。'
|
||||
: '未能加载借用记录,请重试。'
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('获取借用记录失败:', error)
|
||||
} finally {
|
||||
if (listRequests.isCurrent(request)) loading.value = false
|
||||
}
|
||||
@ -284,13 +298,14 @@ const handleReset = () => {
|
||||
}
|
||||
|
||||
const handleExport = async () => {
|
||||
if (exporting.value || !appliedFilters.value) return
|
||||
if (loading.value || exporting.value || !appliedFilters.value) return
|
||||
exporting.value = true
|
||||
exportError.value = ''
|
||||
try {
|
||||
const response = await exportBorrowRecords(appliedFilters.value)
|
||||
downloadFile(response.data as Blob, '借用记录.xlsx')
|
||||
} catch (error) {
|
||||
console.error('导出借用记录失败:', error)
|
||||
} catch {
|
||||
exportError.value = '导出失败,请重试。'
|
||||
} finally {
|
||||
exporting.value = false
|
||||
}
|
||||
|
||||
@ -16,10 +16,10 @@
|
||||
<h3 class="text-lg font-semibold text-text-primary">扫码出库</h3>
|
||||
</div>
|
||||
<div class="form-inline-actions">
|
||||
<button type="button" class="btn-primary w-full sm:w-auto text-sm" @click="showCameraScanner = true">
|
||||
<button type="button" class="btn-primary w-full sm:w-auto text-sm" :disabled="loading" @click="showCameraScanner = true">
|
||||
手机扫码
|
||||
</button>
|
||||
<button type="button" class="btn-secondary w-full sm:w-auto text-sm" @click="showManualEntry = !showManualEntry">
|
||||
<button type="button" class="btn-secondary w-full sm:w-auto text-sm" :disabled="loading" @click="showManualEntry = !showManualEntry">
|
||||
{{ showManualEntry ? '收起' : '手动输入' }}
|
||||
</button>
|
||||
</div>
|
||||
@ -32,7 +32,7 @@
|
||||
</div>
|
||||
<div class="scanner-hero__stat">
|
||||
<p class="scanner-hero__stat-label">识别结果</p>
|
||||
<p class="scanner-hero__stat-value">{{ equipmentInfo ? '已识别资产' : '等待扫码' }}</p>
|
||||
<p class="scanner-hero__stat-value">{{ lookupLoading ? '读取中' : equipmentInfo ? '已识别资产' : '等待扫码' }}</p>
|
||||
</div>
|
||||
<div class="scanner-hero__stat">
|
||||
<p class="scanner-hero__stat-label">当前可借</p>
|
||||
@ -40,7 +40,7 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="showManualEntry" class="form-panel">
|
||||
<fieldset v-if="showManualEntry" class="form-panel min-w-0" :disabled="loading">
|
||||
<div class="form-panel__header">
|
||||
<h4 class="form-panel__title">手动输入</h4>
|
||||
</div>
|
||||
@ -109,7 +109,10 @@
|
||||
没有匹配到可借资产。若你已经知道准确编码,也可以直接点“按编码读取”。
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</fieldset>
|
||||
|
||||
<p v-if="lookupLoading" class="mt-4 text-sm text-text-secondary" role="status">正在读取资产…</p>
|
||||
<p v-if="scanError" class="mt-4 text-sm text-status-error" role="alert">{{ scanError }}</p>
|
||||
|
||||
<!-- 资产信息卡片 -->
|
||||
<section v-if="equipmentInfo" class="card mt-6">
|
||||
@ -120,7 +123,7 @@
|
||||
{{ equipmentInfo.status }}
|
||||
</span>
|
||||
</div>
|
||||
<button type="button" class="btn-secondary text-sm" @click="showCameraScanner = true">
|
||||
<button type="button" class="btn-secondary text-sm" :disabled="loading" @click="showCameraScanner = true">
|
||||
重新扫码
|
||||
</button>
|
||||
</div>
|
||||
@ -190,7 +193,7 @@
|
||||
<!-- 借用表单 -->
|
||||
<section v-if="equipmentInfo" class="card">
|
||||
<h3 class="section-title mb-4">使用者信息</h3>
|
||||
<div class="space-y-4">
|
||||
<fieldset class="min-w-0 space-y-4" :disabled="loading">
|
||||
<div class="field-stack">
|
||||
<label class="field-label">使用者 *</label>
|
||||
<div class="space-y-3">
|
||||
@ -275,6 +278,7 @@
|
||||
placeholder="请输入备注信息"
|
||||
></textarea>
|
||||
</div>
|
||||
<p v-if="submitError" class="text-sm text-status-error" role="alert">{{ submitError }}</p>
|
||||
<div class="mobile-sticky-actions md:static">
|
||||
<button
|
||||
@click="handleSubmit"
|
||||
@ -284,7 +288,7 @@
|
||||
{{ loading ? '提交中...' : '确认出库' }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</fieldset>
|
||||
</section>
|
||||
|
||||
<!-- 成功消息 -->
|
||||
@ -317,6 +321,7 @@ import { getChildren } from '@/api/mount'
|
||||
import type { Equipment } from '@/types'
|
||||
import type { ChildEquipment } from '@/api/mount'
|
||||
import { formatCurrency, playBeepSound, playErrorSound } from '@/utils/format'
|
||||
import { createRequestScope } from '@/utils/requestScope'
|
||||
import CameraScannerModal from '@/components/CameraScannerModal.vue'
|
||||
import { canSubmitBorrowScan } from './borrowScanState'
|
||||
import {
|
||||
@ -346,6 +351,11 @@ const successInfo = ref<{
|
||||
borrow_time: string
|
||||
} | null>(null)
|
||||
const loading = ref(false)
|
||||
const lookupLoading = ref(false)
|
||||
const scanError = ref('')
|
||||
const submitError = ref('')
|
||||
const lookupScope = createRequestScope()
|
||||
const manualSearchScope = createRequestScope()
|
||||
|
||||
const borrowForm = ref({
|
||||
expected_return_time: '',
|
||||
@ -361,7 +371,6 @@ const selectedPersonId = ref<number | null>(null)
|
||||
const persons = ref<PersonOption[]>([])
|
||||
let equipmentSearchTimer: number | null = null
|
||||
let personSearchTimer: number | null = null
|
||||
let latestEquipmentRequestId = 0
|
||||
let latestPersonRequestId = 0
|
||||
const personSearchLoading = ref(false)
|
||||
|
||||
@ -369,7 +378,7 @@ const canSubmit = computed(() => {
|
||||
return canSubmitBorrowScan({
|
||||
hasEquipment: Boolean(equipmentInfo.value && equipmentInfo.value.status !== '已丢失'),
|
||||
selectedPersonId: selectedPersonId.value,
|
||||
loading: loading.value
|
||||
loading: loading.value || lookupLoading.value
|
||||
})
|
||||
})
|
||||
|
||||
@ -423,6 +432,7 @@ const focusManualInput = () => {
|
||||
}
|
||||
|
||||
const clearManualSearch = () => {
|
||||
manualSearchScope.begin()
|
||||
manualKeyword.value = ''
|
||||
manualSearchResults.value = []
|
||||
manualSearchLoading.value = false
|
||||
@ -434,38 +444,41 @@ const handleCameraDetected = async (value: string) => {
|
||||
|
||||
const handleScan = async (rawCode = scanCode.value) => {
|
||||
const normalizedCode = rawCode.trim().toUpperCase()
|
||||
if (!normalizedCode) {
|
||||
return
|
||||
}
|
||||
if (loading.value || !normalizedCode) return
|
||||
|
||||
const request = lookupScope.begin()
|
||||
const searchAtLookup = manualKeyword.value
|
||||
lookupLoading.value = true
|
||||
scanError.value = ''
|
||||
submitError.value = ''
|
||||
equipmentInfo.value = null
|
||||
successInfo.value = null
|
||||
resetBorrowDraftState()
|
||||
try {
|
||||
const response = await scanEquipment(normalizedCode)
|
||||
if (response.data) {
|
||||
equipmentInfo.value = response.data
|
||||
successInfo.value = null
|
||||
resetBorrowDraftState()
|
||||
playBeepSound()
|
||||
if (!lookupScope.isCurrent(request)) return
|
||||
if (!response.data) throw new Error('未找到资产,请核对资产编码')
|
||||
|
||||
// 获取已挂载的子资产
|
||||
try {
|
||||
const childrenResponse = await getChildren(response.data.id)
|
||||
if (childrenResponse.data) {
|
||||
mountedChildren.value = childrenResponse.data.children
|
||||
mountedChildrenValue.value = childrenResponse.data.total_children_value
|
||||
}
|
||||
} catch (e) {
|
||||
// 忽略获取子资产失败的错误
|
||||
}
|
||||
|
||||
// 清空扫码框,准备下次扫码
|
||||
scanCode.value = ''
|
||||
const children = await getChildren(response.data.id).catch(() => null)
|
||||
if (!lookupScope.isCurrent(request)) return
|
||||
equipmentInfo.value = response.data
|
||||
if (children?.data) {
|
||||
mountedChildren.value = children.data.children
|
||||
mountedChildrenValue.value = children.data.total_children_value
|
||||
}
|
||||
playBeepSound()
|
||||
scanCode.value = ''
|
||||
if (manualKeyword.value === searchAtLookup) {
|
||||
clearManualSearch()
|
||||
focusManualInput()
|
||||
}
|
||||
} catch (error: any) {
|
||||
if (!lookupScope.isCurrent(request)) return
|
||||
playErrorSound()
|
||||
alert(error.message || '扫码失败,请检查资产编码是否正确')
|
||||
scanError.value = error?.message || '扫码失败,请检查资产编码是否正确'
|
||||
scanCode.value = ''
|
||||
} finally {
|
||||
if (lookupScope.isCurrent(request)) lookupLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
@ -477,7 +490,7 @@ const fetchManualSearchResults = async (keyword: string) => {
|
||||
return
|
||||
}
|
||||
|
||||
const requestId = ++latestEquipmentRequestId
|
||||
const requestId = manualSearchScope.begin()
|
||||
manualSearchLoading.value = true
|
||||
|
||||
try {
|
||||
@ -488,34 +501,37 @@ const fetchManualSearchResults = async (keyword: string) => {
|
||||
keyword: normalizedKeyword
|
||||
})
|
||||
|
||||
if (requestId !== latestEquipmentRequestId) {
|
||||
if (!manualSearchScope.isCurrent(requestId)) {
|
||||
return
|
||||
}
|
||||
|
||||
manualSearchResults.value = filterManualBorrowCandidates(response.data.list, normalizedKeyword) as Equipment[]
|
||||
} catch (error) {
|
||||
if (requestId === latestEquipmentRequestId) {
|
||||
if (manualSearchScope.isCurrent(requestId)) {
|
||||
manualSearchResults.value = []
|
||||
}
|
||||
console.error('搜索可借资产失败', error)
|
||||
} finally {
|
||||
if (requestId === latestEquipmentRequestId) {
|
||||
if (manualSearchScope.isCurrent(requestId)) {
|
||||
manualSearchLoading.value = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const selectManualSearchResult = async (equipment: Equipment) => {
|
||||
if (loading.value) return
|
||||
manualKeyword.value = equipment.equipment_code
|
||||
await handleScan(equipment.equipment_code)
|
||||
}
|
||||
|
||||
const selectPerson = (person: PersonOption) => {
|
||||
if (loading.value || lookupLoading.value) return
|
||||
selectedPersonId.value = person.id
|
||||
personKeyword.value = buildManualBorrowPersonDisplay(person)
|
||||
}
|
||||
|
||||
const handlePersonKeywordSubmit = () => {
|
||||
if (loading.value || lookupLoading.value) return
|
||||
const preferredPerson = findPreferredManualBorrowPerson(topFilteredPersons.value, personKeyword.value)
|
||||
|
||||
if (preferredPerson) {
|
||||
@ -535,7 +551,7 @@ const handlePersonKeywordSubmit = () => {
|
||||
|
||||
const handleManualSubmit = async () => {
|
||||
const keyword = manualKeyword.value.trim()
|
||||
if (!keyword) {
|
||||
if (loading.value || !keyword) {
|
||||
return
|
||||
}
|
||||
|
||||
@ -556,51 +572,42 @@ const handleManualSubmit = async () => {
|
||||
|
||||
const handleSubmit = async () => {
|
||||
if (!canSubmit.value) return
|
||||
if (!equipmentInfo.value || selectedPersonId.value === null || Number.isNaN(selectedPersonId.value)) {
|
||||
return
|
||||
}
|
||||
const equipment = equipmentInfo.value
|
||||
const personId = selectedPersonId.value
|
||||
if (!equipment || personId === null) return
|
||||
const person = selectedPerson.value
|
||||
const draft = { ...borrowForm.value }
|
||||
const request = lookupScope.begin()
|
||||
|
||||
loading.value = true
|
||||
submitError.value = ''
|
||||
try {
|
||||
const response = await scanBorrow({
|
||||
equipment_code: equipmentInfo.value.equipment_code,
|
||||
person_id: Number(selectedPersonId.value),
|
||||
expected_return_time: borrowForm.value.is_long_term
|
||||
? undefined
|
||||
: borrowForm.value.expected_return_time || undefined,
|
||||
notes: borrowForm.value.notes || undefined,
|
||||
is_long_term: borrowForm.value.is_long_term
|
||||
equipment_code: equipment.equipment_code,
|
||||
person_id: personId,
|
||||
expected_return_time: draft.is_long_term ? undefined : draft.expected_return_time || undefined,
|
||||
notes: draft.notes || undefined,
|
||||
is_long_term: draft.is_long_term
|
||||
})
|
||||
if (!lookupScope.isCurrent(request)) return
|
||||
if (response.data) {
|
||||
alert('出库成功!')
|
||||
const personDisplay = selectedPerson.value
|
||||
? `${selectedPerson.value.nickname}(${selectedPerson.value.real_name})`
|
||||
: `ID ${selectedPersonId.value}`
|
||||
successInfo.value = {
|
||||
equipment_name: equipmentInfo.value.equipment_name,
|
||||
equipment_code: equipmentInfo.value.equipment_code,
|
||||
person_display: personDisplay,
|
||||
equipment_name: equipment.equipment_name,
|
||||
equipment_code: equipment.equipment_code,
|
||||
person_display: person ? `${person.nickname}(${person.real_name})` : `ID ${personId}`,
|
||||
borrow_time: response.data.borrow_time
|
||||
? new Date(response.data.borrow_time).toLocaleString()
|
||||
: new Date().toLocaleString()
|
||||
}
|
||||
if (typeof response.data.remaining_quantity === 'number') {
|
||||
equipmentInfo.value.remaining_quantity = response.data.remaining_quantity
|
||||
}
|
||||
if (response.data.equipment_status) {
|
||||
equipmentInfo.value.status = response.data.equipment_status
|
||||
} else if (equipmentInfo.value.remaining_quantity === 0) {
|
||||
equipmentInfo.value.status = '已借出'
|
||||
}
|
||||
equipmentInfo.value = null
|
||||
resetBorrowDraftState()
|
||||
clearManualSearch()
|
||||
focusManualInput()
|
||||
}
|
||||
} catch (error: any) {
|
||||
alert(error.message || '出库失败')
|
||||
if (lookupScope.isCurrent(request)) submitError.value = error?.message || '出库失败'
|
||||
} finally {
|
||||
loading.value = false
|
||||
if (lookupScope.isCurrent(request)) loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
@ -640,6 +647,8 @@ const fetchPersons = async (keyword = '') => {
|
||||
watch(
|
||||
() => manualKeyword.value,
|
||||
(value) => {
|
||||
manualSearchScope.begin()
|
||||
manualSearchResults.value = []
|
||||
if (equipmentSearchTimer) {
|
||||
window.clearTimeout(equipmentSearchTimer)
|
||||
}
|
||||
@ -700,6 +709,8 @@ onMounted(() => {
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
lookupScope.dispose()
|
||||
manualSearchScope.dispose()
|
||||
if (equipmentSearchTimer) {
|
||||
window.clearTimeout(equipmentSearchTimer)
|
||||
}
|
||||
@ -710,8 +721,16 @@ onUnmounted(() => {
|
||||
|
||||
watch(
|
||||
() => route.query.equipment_code,
|
||||
() => {
|
||||
loadEquipmentFromRoute()
|
||||
(code, previousCode) => {
|
||||
if (code) {
|
||||
void loadEquipmentFromRoute()
|
||||
} else if (previousCode && !loading.value) {
|
||||
lookupScope.begin()
|
||||
lookupLoading.value = false
|
||||
equipmentInfo.value = null
|
||||
scanError.value = ''
|
||||
resetBorrowDraftState()
|
||||
}
|
||||
}
|
||||
)
|
||||
</script>
|
||||
|
||||
@ -14,10 +14,10 @@
|
||||
<h3 class="text-lg font-semibold text-text-primary">扫码归还</h3>
|
||||
</div>
|
||||
<div class="form-inline-actions">
|
||||
<button type="button" class="btn-primary w-full sm:w-auto text-sm" @click="showCameraScanner = true">
|
||||
<button type="button" class="btn-primary w-full sm:w-auto text-sm" :disabled="loading" @click="showCameraScanner = true">
|
||||
手机扫码
|
||||
</button>
|
||||
<button type="button" class="btn-secondary w-full sm:w-auto text-sm" @click="showManualEntry = !showManualEntry">
|
||||
<button type="button" class="btn-secondary w-full sm:w-auto text-sm" :disabled="loading" @click="showManualEntry = !showManualEntry">
|
||||
{{ showManualEntry ? '收起' : '手动输入' }}
|
||||
</button>
|
||||
</div>
|
||||
@ -26,7 +26,7 @@
|
||||
<div class="scanner-hero__stats">
|
||||
<div class="scanner-hero__stat">
|
||||
<p class="scanner-hero__stat-label">当前进度</p>
|
||||
<p class="scanner-hero__stat-value">{{ borrowRecordInfo ? '待确认归还' : '等待扫码' }}</p>
|
||||
<p class="scanner-hero__stat-value">{{ lookupLoading ? '读取中' : borrowRecordInfo ? '待确认归还' : '等待扫码' }}</p>
|
||||
</div>
|
||||
<div class="scanner-hero__stat">
|
||||
<p class="scanner-hero__stat-label">借用记录</p>
|
||||
@ -45,6 +45,7 @@
|
||||
<div
|
||||
v-if="pageNotice"
|
||||
class="rounded-lg border px-4 py-3 text-sm"
|
||||
:role="pageNotice.type === 'error' ? 'alert' : 'status'"
|
||||
:class="pageNotice.type === 'success'
|
||||
? 'border-status-success/30 bg-status-success/10 text-status-success'
|
||||
: pageNotice.type === 'warning'
|
||||
@ -54,7 +55,9 @@
|
||||
{{ pageNotice.message }}
|
||||
</div>
|
||||
|
||||
<div v-if="showManualEntry" class="form-panel">
|
||||
<p v-if="lookupLoading" class="text-sm text-text-secondary" role="status">正在读取资产和借用记录…</p>
|
||||
|
||||
<fieldset v-if="showManualEntry" class="form-panel min-w-0" :disabled="loading">
|
||||
<div class="form-panel__header">
|
||||
<h4 class="form-panel__title">手动输入</h4>
|
||||
</div>
|
||||
@ -68,7 +71,6 @@
|
||||
class="input"
|
||||
placeholder="输入资产编码 / 名称 / 型号 / 地址搜索"
|
||||
@keyup.enter="handleManualAssetSubmit"
|
||||
@focus="handleFocus"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
@ -129,7 +131,7 @@
|
||||
没有匹配到需要处理的借出资产。可尝试资产编码、资产名称、型号或地址。
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</fieldset>
|
||||
|
||||
<section v-if="borrowRecordInfo" class="card mt-6">
|
||||
<div class="list-header">
|
||||
@ -137,7 +139,7 @@
|
||||
<h3 class="section-title">资产信息</h3>
|
||||
<span class="badge badge-warning">已借出</span>
|
||||
</div>
|
||||
<button type="button" class="btn-secondary text-sm" @click="showCameraScanner = true">
|
||||
<button type="button" class="btn-secondary text-sm" :disabled="loading" @click="showCameraScanner = true">
|
||||
重新扫码
|
||||
</button>
|
||||
</div>
|
||||
@ -180,12 +182,13 @@
|
||||
type="text"
|
||||
class="input"
|
||||
placeholder="输入花名 / 姓名 / 工号 / 部门搜索"
|
||||
:disabled="loading"
|
||||
@keyup.enter="handleRecordKeywordSubmit"
|
||||
/>
|
||||
<p class="text-xs text-text-tertiary">
|
||||
{{ borrowRecordInfo.borrow_records.length > 1
|
||||
? '这台资产存在多条未归还记录,请搜索并点选正确使用者。'
|
||||
: '这台资产当前只有 1 条未归还记录,系统已自动帮你选中。' }}
|
||||
{{ borrowRecordInfo.borrow_records.length === 1 && selectedBorrowRecordId
|
||||
? '这台资产当前只有 1 条未归还记录,已选中。'
|
||||
: '请搜索并点选正确的归还使用者。' }}
|
||||
</p>
|
||||
<div v-if="showRecordSearchResults" class="space-y-2">
|
||||
<div class="flex items-center justify-between gap-3 px-1">
|
||||
@ -201,6 +204,7 @@
|
||||
type="button"
|
||||
class="touch-option"
|
||||
:class="{ 'is-active': selectedBorrowRecordId === record.id }"
|
||||
:disabled="loading"
|
||||
@click="selectBorrowRecord(record)"
|
||||
>
|
||||
<div class="flex items-start justify-between gap-3">
|
||||
@ -308,7 +312,7 @@
|
||||
|
||||
<section v-if="borrowRecordInfo" class="card">
|
||||
<h3 class="section-title mb-4">归还信息</h3>
|
||||
<div class="field-grid">
|
||||
<fieldset class="field-grid min-w-0" :disabled="loading">
|
||||
<div class="field-stack">
|
||||
<label class="field-label">归还状态</label>
|
||||
<select v-model="returnInfo.return_condition" class="select">
|
||||
@ -326,7 +330,7 @@
|
||||
placeholder="请输入备注信息"
|
||||
></textarea>
|
||||
</div>
|
||||
</div>
|
||||
</fieldset>
|
||||
<div class="mobile-sticky-actions md:static md:m-0 md:border-0 md:bg-transparent md:p-0 mt-4">
|
||||
<button
|
||||
@click="handleSubmit"
|
||||
@ -342,7 +346,8 @@
|
||||
|
||||
<script setup lang="ts">
|
||||
import { getReturnCompletionText, submitReturnWithConfirmation } from '@/utils/returnConfirmation'
|
||||
import { ref, onMounted, nextTick, computed, watch } from 'vue'
|
||||
import { ref, onMounted, onUnmounted, nextTick, computed, watch } from 'vue'
|
||||
import { createRequestScope } from '@/utils/requestScope'
|
||||
import { useRoute } from 'vue-router'
|
||||
import { getBorrowRecordByCode, scanReturn, searchReturnAssets } from '@/api/borrow'
|
||||
import { getChildren } from '@/api/mount'
|
||||
@ -392,6 +397,9 @@ const showCameraScanner = ref(false)
|
||||
const showManualEntry = ref(window.matchMedia('(pointer: fine)').matches)
|
||||
const borrowRecordInfo = ref<BorrowRecordInfo | null>(null)
|
||||
const loading = ref(false)
|
||||
const lookupLoading = ref(false)
|
||||
const lookupScope = createRequestScope()
|
||||
const manualSearchScope = createRequestScope()
|
||||
const childrenSnapshot = ref<ChildSnapshot[]>([])
|
||||
const currentChildren = ref<ChildEquipment[]>([])
|
||||
const pageNotice = ref<{ type: 'success' | 'warning' | 'error'; message: string } | null>(null)
|
||||
@ -417,15 +425,13 @@ const manualAssetSearchResults = ref<ManualReturnAssetCandidate[]>([])
|
||||
const manualAssetSearchLoading = ref(false)
|
||||
const recordKeyword = ref('')
|
||||
const selectedBorrowRecordId = ref<number | null>(null)
|
||||
const appliedRouteQuickReturnKey = ref('')
|
||||
let assetSearchTimer: number | null = null
|
||||
let latestAssetRequestId = 0
|
||||
|
||||
const canSubmit = computed(() =>
|
||||
canSubmitReturnScan({
|
||||
hasBorrowRecordInfo: Boolean(borrowRecordInfo.value),
|
||||
hasBorrowRecordInfo: Boolean(borrowRecordInfo.value && selectedBorrowRecord.value),
|
||||
selectedBorrowRecordId: selectedBorrowRecordId.value,
|
||||
loading: loading.value
|
||||
loading: loading.value || lookupLoading.value
|
||||
})
|
||||
)
|
||||
|
||||
@ -477,6 +483,7 @@ const getManualAssetBadgeText = (asset: ManualReturnAssetCandidate) =>
|
||||
isBorrowRecordMissingAsset(asset) ? '借用单缺失' : `待归还 ${asset.active_borrow_count}`
|
||||
|
||||
const selectBorrowRecord = (record: BorrowRecord) => {
|
||||
if (loading.value) return
|
||||
selectedBorrowRecordId.value = record.id
|
||||
recordKeyword.value = buildManualReturnRecordDisplay(record)
|
||||
}
|
||||
@ -503,15 +510,12 @@ const resetCurrentFlow = () => {
|
||||
resetReturnForm()
|
||||
}
|
||||
|
||||
const handleFocus = () => {
|
||||
pageNotice.value = null
|
||||
}
|
||||
|
||||
const handleCameraDetected = async (value: string) => {
|
||||
await handleScan(value.trim())
|
||||
}
|
||||
|
||||
const clearManualAssetSearch = () => {
|
||||
manualSearchScope.begin()
|
||||
manualAssetKeyword.value = ''
|
||||
manualAssetSearchResults.value = []
|
||||
manualAssetSearchLoading.value = false
|
||||
@ -556,12 +560,12 @@ const fetchManualAssetSearchResults = async (keyword: string) => {
|
||||
return
|
||||
}
|
||||
|
||||
const requestId = ++latestAssetRequestId
|
||||
const requestId = manualSearchScope.begin()
|
||||
manualAssetSearchLoading.value = true
|
||||
|
||||
try {
|
||||
const response = await searchReturnAssets({ keyword: normalizedKeyword })
|
||||
if (requestId !== latestAssetRequestId) {
|
||||
if (!manualSearchScope.isCurrent(requestId)) {
|
||||
return
|
||||
}
|
||||
|
||||
@ -570,20 +574,23 @@ const fetchManualAssetSearchResults = async (keyword: string) => {
|
||||
normalizedKeyword
|
||||
)
|
||||
} catch (error) {
|
||||
if (requestId === latestAssetRequestId) {
|
||||
if (manualSearchScope.isCurrent(requestId)) {
|
||||
manualAssetSearchResults.value = []
|
||||
}
|
||||
console.error('搜索待归还资产失败', error)
|
||||
} finally {
|
||||
if (requestId === latestAssetRequestId) {
|
||||
if (manualSearchScope.isCurrent(requestId)) {
|
||||
manualAssetSearchLoading.value = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const selectManualAsset = async (asset: ManualReturnAssetCandidate) => {
|
||||
if (loading.value || showBorrowAnomalyHandler.value) return
|
||||
manualAssetKeyword.value = asset.equipment_code
|
||||
if (isBorrowRecordMissingAsset(asset)) {
|
||||
lookupScope.begin()
|
||||
lookupLoading.value = false
|
||||
resetCurrentFlow()
|
||||
if (asset.can_handle_borrow_anomaly) {
|
||||
openBorrowAnomalyHandler(asset)
|
||||
@ -606,7 +613,7 @@ const selectManualAsset = async (asset: ManualReturnAssetCandidate) => {
|
||||
|
||||
const handleManualAssetSubmit = async () => {
|
||||
const keyword = manualAssetKeyword.value.trim()
|
||||
if (!keyword) {
|
||||
if (loading.value || !keyword) {
|
||||
return
|
||||
}
|
||||
|
||||
@ -631,6 +638,7 @@ const handleManualAssetSubmit = async () => {
|
||||
}
|
||||
|
||||
const handleRecordKeywordSubmit = () => {
|
||||
if (loading.value) return
|
||||
const preferredRecord = findPreferredManualReturnRecordCandidate(
|
||||
filteredReturnRecords.value,
|
||||
recordKeyword.value
|
||||
@ -672,64 +680,60 @@ const normalizeQueryNumber = (value: unknown) => {
|
||||
return Number.isInteger(parsed) && parsed > 0 ? parsed : null
|
||||
}
|
||||
|
||||
const handleScan = async (rawCode: string) => {
|
||||
const handleScan = async (rawCode: string, requestedRecordId: number | null = null) => {
|
||||
const normalizedCode = rawCode.trim().toUpperCase()
|
||||
if (!normalizedCode) {
|
||||
return false
|
||||
}
|
||||
if (loading.value || showBorrowAnomalyHandler.value || !normalizedCode) return false
|
||||
|
||||
const request = lookupScope.begin()
|
||||
const searchAtLookup = manualAssetKeyword.value
|
||||
lookupLoading.value = true
|
||||
pageNotice.value = null
|
||||
resetCurrentFlow()
|
||||
try {
|
||||
const response = await getBorrowRecordByCode(normalizedCode)
|
||||
if (response.data) {
|
||||
borrowRecordInfo.value = response.data
|
||||
childrenSnapshot.value = []
|
||||
currentChildren.value = []
|
||||
selectedBorrowRecordId.value = null
|
||||
recordKeyword.value = ''
|
||||
resetReturnForm()
|
||||
playBeepSound()
|
||||
if (!lookupScope.isCurrent(request)) return false
|
||||
const info = response.data
|
||||
if (!info) throw new Error('未找到借用记录,请核对资产编码')
|
||||
|
||||
const equipmentId = response.data.borrow_records?.[0]?.equipment_id
|
||||
if (equipmentId) {
|
||||
try {
|
||||
const childrenResponse = await getChildren(equipmentId)
|
||||
if (childrenResponse.data) {
|
||||
currentChildren.value = childrenResponse.data.children
|
||||
}
|
||||
} catch {
|
||||
// 忽略查询当前子资产失败
|
||||
}
|
||||
}
|
||||
|
||||
if (response.data.borrow_records.length === 1) {
|
||||
selectBorrowRecord(response.data.borrow_records[0])
|
||||
pageNotice.value = {
|
||||
type: 'success',
|
||||
message: `已读取 ${response.data.equipment_name} 的借用记录,可以直接确认归还。`
|
||||
}
|
||||
} else {
|
||||
pageNotice.value = {
|
||||
type: 'warning',
|
||||
message: `已读取 ${response.data.equipment_name},请先选择正确的归还使用者。`
|
||||
}
|
||||
}
|
||||
const equipmentId = info.borrow_records[0]?.equipment_id
|
||||
const children = equipmentId ? await getChildren(equipmentId).catch(() => null) : null
|
||||
if (!lookupScope.isCurrent(request)) return false
|
||||
borrowRecordInfo.value = info
|
||||
currentChildren.value = children?.data?.children || []
|
||||
playBeepSound()
|
||||
|
||||
const record = requestedRecordId
|
||||
? info.borrow_records.find((entry) => entry.id === requestedRecordId)
|
||||
: info.borrow_records.length === 1 ? info.borrow_records[0] : undefined
|
||||
if (record) selectBorrowRecord(record)
|
||||
pageNotice.value = record ? {
|
||||
type: 'success',
|
||||
message: `已读取 ${info.equipment_name} 的借用记录,可以确认归还。`
|
||||
} : {
|
||||
type: 'warning',
|
||||
message: requestedRecordId
|
||||
? `没有找到 ${info.equipment_name} 的指定借用记录,请手动选择归还使用者。`
|
||||
: `已读取 ${info.equipment_name},请先选择正确的归还使用者。`
|
||||
}
|
||||
if (manualAssetKeyword.value === searchAtLookup) {
|
||||
clearManualAssetSearch()
|
||||
focusScanInput()
|
||||
return true
|
||||
}
|
||||
return true
|
||||
} catch (error: any) {
|
||||
if (!lookupScope.isCurrent(request)) return false
|
||||
playErrorSound()
|
||||
if (error?.status === 409) {
|
||||
try {
|
||||
const anomalySearch = await searchReturnAssets({ keyword: normalizedCode })
|
||||
if (!lookupScope.isCurrent(request)) return false
|
||||
const preferredAsset = findPreferredManualReturnAssetCandidate(
|
||||
filterManualReturnAssetCandidates(anomalySearch.data || [], normalizedCode),
|
||||
normalizedCode
|
||||
)
|
||||
|
||||
if (preferredAsset && isBorrowRecordMissingAsset(preferredAsset)) {
|
||||
manualAssetKeyword.value = preferredAsset.equipment_code
|
||||
if (manualAssetKeyword.value === searchAtLookup) manualAssetKeyword.value = preferredAsset.equipment_code
|
||||
if (preferredAsset.can_handle_borrow_anomaly) {
|
||||
openBorrowAnomalyHandler(preferredAsset)
|
||||
pageNotice.value = {
|
||||
@ -755,66 +759,66 @@ const handleScan = async (rawCode: string) => {
|
||||
}
|
||||
}
|
||||
|
||||
if (!lookupScope.isCurrent(request)) return false
|
||||
pageNotice.value = {
|
||||
type: 'error',
|
||||
message: error.message || '扫码失败,请检查资产编码是否正确'
|
||||
message: error?.message || '扫码失败,请检查资产编码是否正确'
|
||||
}
|
||||
focusScanInput()
|
||||
} finally {
|
||||
if (lookupScope.isCurrent(request)) lookupLoading.value = false
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
const handleSubmit = async () => {
|
||||
if (!borrowRecordInfo.value) {
|
||||
return
|
||||
}
|
||||
|
||||
if (!canSubmit.value) return
|
||||
const equipment = borrowRecordInfo.value
|
||||
const record = selectedBorrowRecord.value
|
||||
|
||||
if (!record) {
|
||||
pageNotice.value = {
|
||||
type: 'warning',
|
||||
message: '请选择归还使用者后再确认入库。'
|
||||
}
|
||||
return
|
||||
}
|
||||
if (!equipment || !record) return
|
||||
const draft = { ...returnInfo.value }
|
||||
const request = lookupScope.begin()
|
||||
|
||||
loading.value = true
|
||||
pageNotice.value = null
|
||||
try {
|
||||
const result = await submitReturnWithConfirmation({
|
||||
equipment_code: borrowRecordInfo.value.equipment_code,
|
||||
return_condition: returnInfo.value.return_condition,
|
||||
notes: returnInfo.value.notes || undefined,
|
||||
equipment_code: equipment.equipment_code,
|
||||
return_condition: draft.return_condition,
|
||||
notes: draft.notes || undefined,
|
||||
person_id: record.person_id,
|
||||
borrow_record_id: record.id
|
||||
}, scanReturn, (message) => window.confirm(message))
|
||||
if (!result) return
|
||||
}, scanReturn, (message) => lookupScope.isCurrent(request) && window.confirm(message))
|
||||
if (!lookupScope.isCurrent(request) || !result) return
|
||||
|
||||
playBeepSound()
|
||||
returnSuccessCount.value += 1
|
||||
pageNotice.value = {
|
||||
type: 'success',
|
||||
message: `${borrowRecordInfo.value.equipment_name} ${getReturnCompletionText(returnInfo.value.return_condition)},可以继续扫码下一件。`
|
||||
message: `${equipment.equipment_name} ${getReturnCompletionText(draft.return_condition)},可以继续扫码下一件。`
|
||||
}
|
||||
resetCurrentFlow()
|
||||
clearManualAssetSearch()
|
||||
focusScanInput()
|
||||
} catch (error: any) {
|
||||
if (!lookupScope.isCurrent(request)) return
|
||||
playErrorSound()
|
||||
pageNotice.value = {
|
||||
type: 'error',
|
||||
message: error.message || '入库失败,请稍后再试'
|
||||
message: error?.message || '入库失败,请稍后再试'
|
||||
}
|
||||
focusScanInput()
|
||||
} finally {
|
||||
loading.value = false
|
||||
if (lookupScope.isCurrent(request)) loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
watch(
|
||||
() => manualAssetKeyword.value,
|
||||
(value) => {
|
||||
manualSearchScope.begin()
|
||||
manualAssetSearchResults.value = []
|
||||
if (assetSearchTimer) {
|
||||
window.clearTimeout(assetSearchTimer)
|
||||
}
|
||||
@ -864,43 +868,17 @@ watch(
|
||||
)
|
||||
|
||||
watch(
|
||||
() => [route.query.equipmentCode, route.query.borrowRecordId],
|
||||
async ([equipmentCodeQuery, borrowRecordIdQuery]) => {
|
||||
[() => route.query.equipmentCode, () => route.query.borrowRecordId],
|
||||
([equipmentCodeQuery, borrowRecordIdQuery], previous) => {
|
||||
const equipmentCode = normalizeQueryString(equipmentCodeQuery)
|
||||
const borrowRecordId = normalizeQueryNumber(borrowRecordIdQuery)
|
||||
|
||||
if (!equipmentCode) {
|
||||
appliedRouteQuickReturnKey.value = ''
|
||||
return
|
||||
if (equipmentCode) {
|
||||
void handleScan(equipmentCode, normalizeQueryNumber(borrowRecordIdQuery))
|
||||
} else if (normalizeQueryString(previous?.[0]) && !loading.value) {
|
||||
lookupScope.begin()
|
||||
lookupLoading.value = false
|
||||
pageNotice.value = null
|
||||
resetCurrentFlow()
|
||||
}
|
||||
|
||||
const quickReturnKey = `${equipmentCode}#${borrowRecordId || ''}`
|
||||
if (appliedRouteQuickReturnKey.value === quickReturnKey) {
|
||||
return
|
||||
}
|
||||
|
||||
const loaded = await handleScan(equipmentCode)
|
||||
if (!loaded || !borrowRecordInfo.value) {
|
||||
return
|
||||
}
|
||||
|
||||
if (borrowRecordId) {
|
||||
const matchedRecord = borrowRecordInfo.value.borrow_records.find((record) => record.id === borrowRecordId)
|
||||
if (matchedRecord) {
|
||||
selectBorrowRecord(matchedRecord)
|
||||
pageNotice.value = {
|
||||
type: 'success',
|
||||
message: `已为 ${borrowRecordInfo.value.equipment_name} 选中 ${matchedRecord.person_nickname} 的归还记录,可以直接确认入库。`
|
||||
}
|
||||
} else {
|
||||
pageNotice.value = {
|
||||
type: 'warning',
|
||||
message: `已打开 ${borrowRecordInfo.value.equipment_name},但没有找到指定的借用记录,请手动选择归还使用者。`
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
appliedRouteQuickReturnKey.value = quickReturnKey
|
||||
},
|
||||
{ immediate: true }
|
||||
)
|
||||
@ -908,4 +886,10 @@ watch(
|
||||
onMounted(() => {
|
||||
focusScanInput()
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
lookupScope.dispose()
|
||||
manualSearchScope.dispose()
|
||||
if (assetSearchTimer) window.clearTimeout(assetSearchTimer)
|
||||
})
|
||||
</script>
|
||||
|
||||
@ -89,6 +89,9 @@
|
||||
|
||||
<!-- 图表区域 -->
|
||||
<div v-if="stats" class="grid gap-4 lg:grid-cols-2">
|
||||
<p v-if="chartError" class="panel text-sm text-text-secondary lg:col-span-2" role="status">
|
||||
图表暂时无法显示,仍可查看统计数字。
|
||||
</p>
|
||||
<!-- 资产状态分布 -->
|
||||
<section class="card">
|
||||
<div class="list-header">
|
||||
@ -98,7 +101,7 @@
|
||||
</div>
|
||||
<span class="badge badge-neutral">已报废历史 {{ formatNumber(stats.disposed_equipment) }}</span>
|
||||
</div>
|
||||
<div ref="statusChartRef" class="h-64"></div>
|
||||
<div v-show="!chartError" ref="statusChartRef" class="h-64"></div>
|
||||
<div class="mt-3 grid grid-cols-2 gap-2 sm:grid-cols-4">
|
||||
<div v-for="item in statusSummaryItems" :key="item.label" class="panel text-center">
|
||||
<p class="text-xs text-text-tertiary">{{ item.label }}</p>
|
||||
@ -116,7 +119,7 @@
|
||||
</div>
|
||||
<span class="badge badge-neutral">TOP 5</span>
|
||||
</div>
|
||||
<div ref="categoryChartRef" class="h-64"></div>
|
||||
<div v-show="!chartError" ref="categoryChartRef" class="h-64"></div>
|
||||
<div class="mt-4 space-y-2">
|
||||
<div
|
||||
v-for="item in topCategories"
|
||||
@ -328,7 +331,7 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onMounted, onUnmounted, ref } from 'vue'
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
import * as echarts from 'echarts'
|
||||
import type { EChartsType } from 'echarts/core'
|
||||
import { getDashboardStats } from '@/api/statistics'
|
||||
import { getBorrowRecordList } from '@/api/borrow'
|
||||
import type { DashboardStats, BorrowRecord } from '@/types'
|
||||
@ -352,6 +355,7 @@ const statusChartRef = ref<HTMLElement>()
|
||||
const categoryChartRef = ref<HTMLElement>()
|
||||
const isLoading = ref(false)
|
||||
const dashboardStatsError = ref('')
|
||||
const chartError = ref(false)
|
||||
const recentRecordsError = ref('')
|
||||
const pendingDisposals = ref<number | null>(null)
|
||||
const pendingDisposalsError = ref(false)
|
||||
@ -360,8 +364,8 @@ const deliveryStatusError = ref(false)
|
||||
const myAssets = ref<MyAssetRecord[]>([])
|
||||
const myAssetsLoading = ref(false)
|
||||
const myAssetsError = ref('')
|
||||
let statusChart: echarts.ECharts | null = null
|
||||
let categoryChart: echarts.ECharts | null = null
|
||||
let statusChart: EChartsType | null = null
|
||||
let categoryChart: EChartsType | null = null
|
||||
|
||||
const canViewReports = computed(() => authStore.can(PERMISSIONS.REPORTS_VIEW))
|
||||
const canBorrow = computed(() => authStore.can(PERMISSIONS.ASSETS_BORROW))
|
||||
@ -529,6 +533,7 @@ const getCategoryBreakdown = (item: DashboardStats['inventory_by_type'][number])
|
||||
const fetchDashboardData = async () => {
|
||||
isLoading.value = true
|
||||
dashboardStatsError.value = ''
|
||||
chartError.value = false
|
||||
recentRecordsError.value = ''
|
||||
try {
|
||||
const [statsResult, recordsResult] = await Promise.allSettled([
|
||||
@ -564,7 +569,7 @@ const fetchDashboardData = async () => {
|
||||
|
||||
if (stats.value) {
|
||||
await nextTick()
|
||||
initCharts()
|
||||
await initCharts()
|
||||
}
|
||||
}
|
||||
|
||||
@ -606,18 +611,22 @@ const fetchMyAssets = async () => {
|
||||
}
|
||||
}
|
||||
|
||||
const initCharts = () => {
|
||||
if (statusChartRef.value && !statusChart) {
|
||||
statusChart = echarts.init(statusChartRef.value)
|
||||
const initCharts = async () => {
|
||||
if (!statusChartRef.value || !categoryChartRef.value) return
|
||||
try {
|
||||
const { init } = await import('@/utils/assetCharts')
|
||||
if (!stats.value || !statusChartRef.value || !categoryChartRef.value) return
|
||||
statusChart ??= init(statusChartRef.value)
|
||||
categoryChart ??= init(categoryChartRef.value)
|
||||
const secondaryText = getComputedStyle(document.documentElement).getPropertyValue('--text-tertiary').trim()
|
||||
updateStatusChart(secondaryText)
|
||||
updateCategoryChart(secondaryText)
|
||||
} catch {
|
||||
chartError.value = true
|
||||
}
|
||||
if (categoryChartRef.value && !categoryChart) {
|
||||
categoryChart = echarts.init(categoryChartRef.value)
|
||||
}
|
||||
updateStatusChart()
|
||||
updateCategoryChart()
|
||||
}
|
||||
|
||||
const updateStatusChart = () => {
|
||||
const updateStatusChart = (secondaryText: string) => {
|
||||
if (!statusChart || !stats.value) return
|
||||
|
||||
statusChart.setOption({
|
||||
@ -625,7 +634,7 @@ const updateStatusChart = () => {
|
||||
legend: {
|
||||
bottom: 0,
|
||||
icon: 'circle',
|
||||
textStyle: { color: '#6e6e6e' }
|
||||
textStyle: { color: secondaryText }
|
||||
},
|
||||
series: [
|
||||
{
|
||||
@ -643,7 +652,7 @@ const updateStatusChart = () => {
|
||||
}, true)
|
||||
}
|
||||
|
||||
const updateCategoryChart = () => {
|
||||
const updateCategoryChart = (secondaryText: string) => {
|
||||
if (!categoryChart || !stats.value) return
|
||||
|
||||
const categories = topCategories.value
|
||||
@ -662,7 +671,7 @@ const updateCategoryChart = () => {
|
||||
xAxis: {
|
||||
type: 'value',
|
||||
splitLine: { lineStyle: { color: '#2a2a2a' } },
|
||||
axisLabel: { color: '#6e6e6e' }
|
||||
axisLabel: { color: secondaryText }
|
||||
},
|
||||
yAxis: {
|
||||
type: 'category',
|
||||
@ -703,8 +712,8 @@ const resizeHandler = () => {
|
||||
|
||||
onMounted(async () => {
|
||||
if (canViewReports.value) {
|
||||
await Promise.all([fetchDashboardData(), fetchRoleSummary()])
|
||||
window.addEventListener('resize', resizeHandler)
|
||||
await Promise.all([fetchDashboardData(), fetchRoleSummary()])
|
||||
} else {
|
||||
await fetchMyAssets()
|
||||
}
|
||||
|
||||
@ -76,14 +76,23 @@
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6V4m0 2a2 2 0 100 4m0-4a2 2 0 110 4m-6 8a2 2 0 100-4m0 4a2 2 0 110-4m0 4v2m0-6V4m6 6v10m6-2a2 2 0 100-4m0 4a2 2 0 110-4m0 4v2m0-6V4" />
|
||||
</svg>
|
||||
</button>
|
||||
<div v-if="canExport || canImport || canApplyDisposal" class="relative">
|
||||
<button @click="showMoreActions = !showMoreActions" class="btn-icon h-10 w-10" title="更多操作">
|
||||
<div v-if="canExport || canImport || canApplyDisposal" class="relative" @keydown.esc="closeMoreActionsOnEscape">
|
||||
<button
|
||||
ref="moreActionsButton"
|
||||
type="button"
|
||||
class="btn-icon h-10 w-10"
|
||||
title="更多操作"
|
||||
aria-controls="equipment-more-actions"
|
||||
:aria-expanded="showMoreActions"
|
||||
@click="showMoreActions = !showMoreActions"
|
||||
>
|
||||
<svg class="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 5v.01M12 12v.01M12 19v.01M12 6a1 1 0 110-2 1 1 0 010 2zm0 7a1 1 0 110-2 1 1 0 010 2zm0 7a1 1 0 110-2 1 1 0 010 2z" />
|
||||
</svg>
|
||||
</button>
|
||||
<div
|
||||
v-if="showMoreActions"
|
||||
id="equipment-more-actions"
|
||||
class="absolute right-0 top-full z-20 mt-2 w-44 rounded-xl border border-border bg-bg-secondary p-2 shadow-[0_18px_44px_rgba(0,0,0,0.36)]"
|
||||
>
|
||||
<button
|
||||
@ -98,14 +107,14 @@
|
||||
<button v-if="canImport" class="w-full rounded-lg px-3 py-2 text-left text-sm text-text-secondary transition hover:bg-bg-hover hover:text-text-primary" @click="downloadTemplateAndClose">
|
||||
下载模板
|
||||
</button>
|
||||
<label v-if="canImport" class="mt-1 flex w-full cursor-pointer rounded-lg px-3 py-2 text-left text-sm text-text-secondary transition hover:bg-bg-hover hover:text-text-primary">
|
||||
<button v-if="canImport" type="button" class="w-full rounded-lg px-3 py-2 text-left text-sm text-text-secondary transition hover:bg-bg-hover hover:text-text-primary" @click="openEquipmentImport">
|
||||
批量导入
|
||||
<input type="file" accept=".csv,.xlsx,.xls" class="hidden" @click="showMoreActions = false" @change="handleFileImport" />
|
||||
</label>
|
||||
</button>
|
||||
<button v-if="canApplyDisposal" type="button" class="w-full rounded-lg px-3 py-2 text-left text-sm text-text-secondary transition hover:bg-bg-hover hover:text-text-primary" @click="openBatchDisposal(true)">
|
||||
导入报废清单
|
||||
</button>
|
||||
</div>
|
||||
<input v-if="canImport" ref="equipmentImportInput" type="file" accept=".csv,.xlsx,.xls" class="hidden" @change="handleFileImport" />
|
||||
</div>
|
||||
<button v-if="hasActiveFilters" @click="handleReset" class="btn-icon h-10 w-10 text-status-error" title="清除筛选">
|
||||
<svg class="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
@ -185,7 +194,7 @@
|
||||
<button v-if="canBorrow" @click="openBatchBorrowModal" class="btn-primary">批量借出</button>
|
||||
<button v-if="canBorrow" @click="openBatchReturnModal" class="btn-secondary btn-secondary--highlight">批量归还</button>
|
||||
<button v-if="canTransfer" @click="openBatchTransferModal" class="btn-secondary">批量转移</button>
|
||||
<button v-if="canApplyDisposal" type="button" @click="openBatchDisposal(false)" class="btn-secondary">批量报废</button>
|
||||
<button v-if="canApplyDisposal" ref="batchDisposalButton" type="button" @click="openBatchDisposal(false)" class="btn-secondary">批量报废</button>
|
||||
<button v-if="canPrintLabels" @click="handleBatchPrintBarcode" class="btn-secondary">打印标签</button>
|
||||
</div>
|
||||
</section>
|
||||
@ -763,7 +772,7 @@
|
||||
<BatchDisposalDialog
|
||||
v-if="canApplyDisposal && batchDisposalIds !== null"
|
||||
:equipment-ids="batchDisposalIds"
|
||||
@close="batchDisposalIds = null"
|
||||
@close="closeBatchDisposal"
|
||||
@submitted="handleBatchDisposalSubmitted"
|
||||
/>
|
||||
|
||||
@ -778,12 +787,11 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, computed, onMounted, watch, onBeforeUnmount } from 'vue'
|
||||
import { ref, computed, nextTick, onMounted, watch, onBeforeUnmount } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
import { PERMISSIONS } from '@/auth/permissions'
|
||||
import { ChevronRightIcon, MagnifyingGlassIcon } from '@heroicons/vue/24/outline'
|
||||
import * as XLSX from 'xlsx'
|
||||
import { getEquipmentList, getEquipmentDetail, deleteEquipment, scanEquipment } from '@/api/equipment'
|
||||
import { indexEquipmentSelection, resolveSelectedEquipmentCodes, type SelectableEquipment } from '@/utils/equipmentSelection'
|
||||
import { parseEquipmentImportRows } from '@/utils/equipmentImport'
|
||||
@ -886,6 +894,9 @@ const showBatchTransferModal = ref(false)
|
||||
const batchDisposalIds = ref<number[] | null>(null)
|
||||
const batchDisposalAppliedCount = ref<number | null>(null)
|
||||
const showMoreActions = ref(false)
|
||||
const moreActionsButton = ref<HTMLButtonElement | null>(null)
|
||||
const batchDisposalButton = ref<HTMLButtonElement | null>(null)
|
||||
const equipmentImportInput = ref<HTMLInputElement | null>(null)
|
||||
const showAdvancedFilters = ref(false)
|
||||
const isExporting = ref(false)
|
||||
const exportFeedback = ref<{
|
||||
@ -1546,6 +1557,13 @@ const handleExportAndClose = async () => {
|
||||
await handleExport()
|
||||
}
|
||||
|
||||
const closeMoreActionsOnEscape = (event: KeyboardEvent) => {
|
||||
if (!showMoreActions.value) return
|
||||
event.preventDefault()
|
||||
showMoreActions.value = false
|
||||
moreActionsButton.value?.focus()
|
||||
}
|
||||
|
||||
const downloadTemplate = () => {
|
||||
const baseUrl = import.meta.env.VITE_API_BASE_URL || '/api'
|
||||
window.open(`${baseUrl}/export/template`, '_blank')
|
||||
@ -1556,16 +1574,23 @@ const downloadTemplateAndClose = () => {
|
||||
downloadTemplate()
|
||||
}
|
||||
|
||||
const openEquipmentImport = () => {
|
||||
showMoreActions.value = false
|
||||
moreActionsButton.value?.focus()
|
||||
equipmentImportInput.value?.click()
|
||||
}
|
||||
|
||||
const handleFileImport = async (e: Event) => {
|
||||
showMoreActions.value = false
|
||||
const file = (e.target as HTMLInputElement).files?.[0]
|
||||
if (!file) return
|
||||
try {
|
||||
const buffer = await file.arrayBuffer()
|
||||
const workbook = XLSX.read(buffer, { type: 'array' })
|
||||
const { read, utils } = await import('xlsx')
|
||||
const workbook = read(buffer, { type: 'array' })
|
||||
const sheetName = workbook.SheetNames[0]
|
||||
const sheet = workbook.Sheets[sheetName]
|
||||
const rows = XLSX.utils.sheet_to_json<unknown[]>(sheet, { header: 1, blankrows: true })
|
||||
const rows = utils.sheet_to_json<unknown[]>(sheet, { header: 1, blankrows: true })
|
||||
|
||||
if (rows.length < 2) {
|
||||
alert('文件内容为空或格式不正确')
|
||||
@ -1573,7 +1598,7 @@ const handleFileImport = async (e: Event) => {
|
||||
return
|
||||
}
|
||||
|
||||
const headerRowOffset = sheet['!ref'] ? XLSX.utils.decode_range(sheet['!ref']).s.r : 0
|
||||
const headerRowOffset = sheet['!ref'] ? utils.decode_range(sheet['!ref']).s.r : 0
|
||||
const equipments = parseEquipmentImportRows(rows, headerRowOffset)
|
||||
|
||||
if (equipments.length === 0) {
|
||||
@ -1811,10 +1836,19 @@ const openBatchDisposal = (importMode: boolean) => {
|
||||
batchDisposalIds.value = importMode ? [] : [...selectedIds.value]
|
||||
}
|
||||
|
||||
const closeBatchDisposal = () => {
|
||||
const fromSelection = Boolean(batchDisposalIds.value?.length)
|
||||
batchDisposalIds.value = null
|
||||
void nextTick(() => {
|
||||
const trigger = (fromSelection ? batchDisposalButton.value : null) ?? moreActionsButton.value
|
||||
trigger?.focus({ preventScroll: true })
|
||||
})
|
||||
}
|
||||
|
||||
const handleBatchDisposalSubmitted = (result: { count: number; equipmentIds: number[] }) => {
|
||||
const submittedIds = new Set(result.equipmentIds)
|
||||
selectedIds.value = selectedIds.value.filter((id) => !submittedIds.has(id))
|
||||
batchDisposalIds.value = null
|
||||
closeBatchDisposal()
|
||||
batchDisposalAppliedCount.value = result.count
|
||||
fetchData()
|
||||
}
|
||||
|
||||
@ -35,6 +35,7 @@
|
||||
v-if="feedback"
|
||||
class="card"
|
||||
:class="getFeedbackClass(feedback.type)"
|
||||
:role="feedback.type === 'error' ? 'alert' : 'status'"
|
||||
>
|
||||
<div class="flex items-start justify-between gap-3">
|
||||
<p class="text-sm font-medium">{{ feedback.text }}</p>
|
||||
@ -57,11 +58,14 @@
|
||||
|
||||
<div v-if="usesBoundIdentity" class="panel">
|
||||
<p class="text-sm font-medium text-text-primary">
|
||||
{{ automaticIdentityError || '正在按当前钉钉账号匹配本人盘点清单...' }}
|
||||
{{ automaticIdentityError || (identityNeedsConfirmation ? '请重新确认本人身份。' : '正在按当前钉钉账号匹配本人盘点清单...') }}
|
||||
</p>
|
||||
<p class="mt-2 text-xs leading-5 text-text-secondary">
|
||||
系统只允许进入本人任务,不能切换成其他员工。
|
||||
</p>
|
||||
<button v-if="identityNeedsConfirmation || automaticIdentityError" type="button" class="btn-primary mt-4" :disabled="confirmingParticipant" @click="confirmBoundIdentity()">
|
||||
{{ confirmingParticipant ? '确认中...' : '重新确认本人身份' }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div v-else-if="requiresDingTalkIdentity" class="panel space-y-4">
|
||||
@ -96,6 +100,7 @@
|
||||
type="button"
|
||||
class="touch-option"
|
||||
:class="{ 'is-active': selectedParticipantId === participant.id }"
|
||||
:disabled="confirmingParticipant"
|
||||
@click="selectedParticipantId = participant.id"
|
||||
>
|
||||
<div class="flex items-start justify-between gap-3">
|
||||
@ -145,7 +150,7 @@
|
||||
<button
|
||||
type="button"
|
||||
class="btn-primary w-full text-sm sm:w-auto"
|
||||
:disabled="isTaskClosed"
|
||||
:disabled="isTaskClosed || actionLocked"
|
||||
@click="showCameraScanner = true"
|
||||
>
|
||||
手机扫码
|
||||
@ -153,11 +158,12 @@
|
||||
<button
|
||||
type="button"
|
||||
class="btn-secondary w-full text-sm sm:w-auto"
|
||||
:disabled="actionLocked"
|
||||
@click="showManualEntry = !showManualEntry"
|
||||
>
|
||||
{{ showManualEntry ? '收起' : '手动输入' }}
|
||||
</button>
|
||||
<button v-if="!usesBoundIdentity && !requiresDingTalkIdentity" type="button" class="btn-secondary w-full text-sm sm:w-auto" @click="switchIdentity">
|
||||
<button v-if="!usesBoundIdentity && !requiresDingTalkIdentity" type="button" class="btn-secondary w-full text-sm sm:w-auto" :disabled="actionLocked" @click="switchIdentity">
|
||||
切换
|
||||
</button>
|
||||
</div>
|
||||
@ -193,16 +199,16 @@
|
||||
type="text"
|
||||
class="input"
|
||||
placeholder="资产编码"
|
||||
:disabled="isTaskClosed"
|
||||
:disabled="isTaskClosed || actionLocked"
|
||||
@keyup.enter="handleSubmitScan"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
class="btn-secondary w-full text-sm sm:w-auto sm:min-w-[100px]"
|
||||
:disabled="isTaskClosed || !scanCode || processingCode === scanCode"
|
||||
:disabled="isTaskClosed || !scanCode || actionLocked"
|
||||
@click="handleSubmitScan"
|
||||
>
|
||||
{{ processingCode === scanCode ? '提交中...' : '提交' }}
|
||||
{{ processingCode && processingCode === scanCode ? '提交中...' : '提交' }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
@ -315,7 +321,7 @@
|
||||
<button
|
||||
type="button"
|
||||
class="btn-primary w-full text-sm"
|
||||
:disabled="processingCode === row.item.equipment_code"
|
||||
:disabled="actionLocked"
|
||||
@click="markItemChecked(row.item)"
|
||||
>
|
||||
{{ processingCode === row.item.equipment_code ? '提交中...' : '确认在我这里' }}
|
||||
@ -323,6 +329,7 @@
|
||||
<button
|
||||
type="button"
|
||||
class="btn-secondary w-full text-sm"
|
||||
:disabled="actionLocked"
|
||||
@click="openExceptionModal(row.item)"
|
||||
>
|
||||
上报异常
|
||||
@ -392,12 +399,12 @@
|
||||
<button
|
||||
type="button"
|
||||
class="table-action table-action--primary"
|
||||
:disabled="processingCode === row.item.equipment_code"
|
||||
:disabled="actionLocked"
|
||||
@click="markItemChecked(row.item)"
|
||||
>
|
||||
{{ processingCode === row.item.equipment_code ? '提交中...' : '确认在我这里' }}
|
||||
</button>
|
||||
<button type="button" class="table-action" @click="openExceptionModal(row.item)">上报异常</button>
|
||||
<button type="button" class="table-action" :disabled="actionLocked" @click="openExceptionModal(row.item)">上报异常</button>
|
||||
</div>
|
||||
<span v-else class="text-xs text-text-tertiary">-</span>
|
||||
</td>
|
||||
@ -436,13 +443,13 @@
|
||||
{{ exceptionTarget.equipment_name }}({{ exceptionTarget.equipment_code }})
|
||||
</p>
|
||||
</div>
|
||||
<button type="button" class="btn-icon" @click="closeExceptionModal">✕</button>
|
||||
<button type="button" class="btn-icon" :disabled="exceptionSubmitting" aria-label="关闭异常上报" @click="closeExceptionModal">✕</button>
|
||||
</div>
|
||||
|
||||
<div class="mt-6 space-y-4">
|
||||
<div class="field-stack">
|
||||
<label class="field-label">异常类型</label>
|
||||
<select v-model="exceptionForm.exception_type" class="select">
|
||||
<select v-model="exceptionForm.exception_type" class="select" :disabled="exceptionSubmitting">
|
||||
<option value="not_found">资产未找到</option>
|
||||
<option value="not_with_me">资产不在本人处</option>
|
||||
</select>
|
||||
@ -455,16 +462,17 @@
|
||||
class="input"
|
||||
rows="3"
|
||||
placeholder="可选,补充说明现场情况"
|
||||
:disabled="exceptionSubmitting"
|
||||
></textarea>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mt-6 flex flex-col gap-3 sm:flex-row sm:justify-end">
|
||||
<button type="button" class="btn-secondary" @click="closeExceptionModal">取消</button>
|
||||
<button type="button" class="btn-secondary" :disabled="exceptionSubmitting" @click="closeExceptionModal">取消</button>
|
||||
<button
|
||||
type="button"
|
||||
class="btn-primary"
|
||||
:disabled="exceptionSubmitting"
|
||||
:disabled="exceptionSubmitting || isTaskClosed"
|
||||
@click="submitException"
|
||||
>
|
||||
{{ exceptionSubmitting ? '提交中...' : '确认上报' }}
|
||||
@ -477,6 +485,7 @@
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onMounted, onUnmounted, reactive, ref, watch } from 'vue'
|
||||
import { createRequestScope } from '@/utils/requestScope'
|
||||
import { ChevronRightIcon } from '@heroicons/vue/24/outline'
|
||||
import { useRoute } from 'vue-router'
|
||||
import CameraScannerModal from '@/components/CameraScannerModal.vue'
|
||||
@ -486,6 +495,7 @@ import {
|
||||
getPublicInventoryItems,
|
||||
getPublicInventoryMe,
|
||||
getPublicInventoryTask,
|
||||
isPublicInventorySessionChanged,
|
||||
searchPublicInventoryParticipants,
|
||||
submitPublicInventoryException,
|
||||
submitPublicInventoryScan
|
||||
@ -524,6 +534,7 @@ const loadingTask = ref(false)
|
||||
const searchingParticipants = ref(false)
|
||||
const confirmingParticipant = ref(false)
|
||||
const automaticIdentityError = ref('')
|
||||
const identityNeedsConfirmation = ref(false)
|
||||
const exceptionSubmitting = ref(false)
|
||||
const feedback = ref<{ type: FeedbackType; text: string } | null>(null)
|
||||
const participantKeyword = ref('')
|
||||
@ -546,8 +557,12 @@ const exceptionForm = reactive<{
|
||||
})
|
||||
|
||||
let participantSearchTimer: number | null = null
|
||||
const taskScope = createRequestScope()
|
||||
let taskRequest = 0
|
||||
|
||||
const taskToken = computed(() => String(route.params.token || ''))
|
||||
const submittingResult = computed(() => Boolean(processingCode.value) || exceptionSubmitting.value)
|
||||
const actionLocked = computed(() => loadingTask.value || submittingResult.value || Boolean(exceptionTarget.value))
|
||||
const usesBoundIdentity = computed(() => Boolean(authStore.isAuthenticated && authStore.user?.person_id))
|
||||
const requiresDingTalkIdentity = computed(() => task.value?.identity_mode === 'dingtalk')
|
||||
const displayedTask = computed(() => {
|
||||
@ -676,77 +691,108 @@ const setFeedback = (type: FeedbackType, text: string) => {
|
||||
feedback.value = { type, text }
|
||||
}
|
||||
|
||||
const loadTaskInfo = async () => {
|
||||
const loadTaskInfo = async (request: number) => {
|
||||
const response = await getPublicInventoryTask(taskToken.value)
|
||||
task.value = response.data
|
||||
if (taskScope.isCurrent(request)) task.value = response.data
|
||||
}
|
||||
|
||||
const loadSessionAndItems = async () => {
|
||||
const loadSessionAndItems = async (request: number, participantId = session.value?.participant.id) => {
|
||||
const token = taskToken.value
|
||||
try {
|
||||
const [sessionResponse, itemsResponse] = await Promise.all([
|
||||
getPublicInventoryMe(),
|
||||
getPublicInventoryItems()
|
||||
getPublicInventoryMe(token, participantId),
|
||||
participantId ? getPublicInventoryItems(token, participantId) : null
|
||||
])
|
||||
|
||||
if (task.value && sessionResponse.data.task.id !== task.value.id) {
|
||||
resetSessionState()
|
||||
if (!taskScope.isCurrent(request)) return false
|
||||
const current = sessionResponse.data
|
||||
if (current.task.id !== task.value?.id || (participantId && current.participant.id !== participantId)) {
|
||||
await recoverIdentity(request)
|
||||
return false
|
||||
}
|
||||
|
||||
session.value = sessionResponse.data
|
||||
items.value = itemsResponse.data.items
|
||||
summary.value = itemsResponse.data.summary
|
||||
const result = itemsResponse || await getPublicInventoryItems(token, current.participant.id)
|
||||
if (!taskScope.isCurrent(request)) return false
|
||||
session.value = current
|
||||
items.value = result.data.items
|
||||
summary.value = result.data.summary
|
||||
identityNeedsConfirmation.value = false
|
||||
return true
|
||||
} catch {
|
||||
resetSessionState()
|
||||
} catch (error) {
|
||||
if (!taskScope.isCurrent(request)) return false
|
||||
if (isPublicInventorySessionChanged(error)) await recoverIdentity(request)
|
||||
else resetSessionState()
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
const searchParticipantsNow = async (keyword = participantKeyword.value) => {
|
||||
const searchParticipantsNow = async (keyword = participantKeyword.value, request = taskRequest) => {
|
||||
if (!taskToken.value || session.value) return
|
||||
|
||||
searchingParticipants.value = true
|
||||
try {
|
||||
const response = await searchPublicInventoryParticipants(taskToken.value, keyword.trim())
|
||||
participants.value = response.data
|
||||
if (taskScope.isCurrent(request)) participants.value = response.data
|
||||
} catch (error: any) {
|
||||
setFeedback('error', error?.message || '搜索盘点参与人失败')
|
||||
if (taskScope.isCurrent(request)) setFeedback('error', error?.message || '搜索盘点参与人失败')
|
||||
} finally {
|
||||
searchingParticipants.value = false
|
||||
if (taskScope.isCurrent(request)) searchingParticipants.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const recoverIdentity = async (request: number) => {
|
||||
resetSessionState()
|
||||
identityNeedsConfirmation.value = true
|
||||
automaticIdentityError.value = ''
|
||||
selectedParticipantId.value = null
|
||||
lastHandledItem.value = null
|
||||
exceptionTarget.value = null
|
||||
scanCode.value = ''
|
||||
showCameraScanner.value = false
|
||||
const message = '当前页面的盘点身份已变化,请重新确认后继续。'
|
||||
setFeedback('error', message)
|
||||
if (!usesBoundIdentity.value && !requiresDingTalkIdentity.value) {
|
||||
await searchParticipantsNow(participantKeyword.value, request)
|
||||
if (taskScope.isCurrent(request) && identityNeedsConfirmation.value) setFeedback('error', message)
|
||||
}
|
||||
}
|
||||
|
||||
const bootstrap = async () => {
|
||||
const request = taskScope.begin()
|
||||
taskRequest = request
|
||||
loadingTask.value = true
|
||||
confirmingParticipant.value = false
|
||||
searchingParticipants.value = false
|
||||
processingCode.value = ''
|
||||
exceptionSubmitting.value = false
|
||||
exceptionTarget.value = null
|
||||
showCameraScanner.value = false
|
||||
scanCode.value = ''
|
||||
feedback.value = null
|
||||
task.value = null
|
||||
resetSessionState()
|
||||
participants.value = []
|
||||
selectedParticipantId.value = null
|
||||
lastHandledItem.value = null
|
||||
automaticIdentityError.value = ''
|
||||
identityNeedsConfirmation.value = false
|
||||
|
||||
try {
|
||||
await loadTaskInfo()
|
||||
const hasSession = await loadSessionAndItems()
|
||||
if (!hasSession) {
|
||||
await loadTaskInfo(request)
|
||||
if (!taskScope.isCurrent(request)) return
|
||||
const hasSession = await loadSessionAndItems(request)
|
||||
if (!taskScope.isCurrent(request)) return
|
||||
if (!hasSession && !identityNeedsConfirmation.value) {
|
||||
if (usesBoundIdentity.value) {
|
||||
try {
|
||||
await confirmCurrentInventoryParticipant(taskToken.value)
|
||||
const confirmed = await loadSessionAndItems()
|
||||
if (!confirmed) throw new Error('钉钉身份已确认,但盘点会话建立失败')
|
||||
setFeedback('success', '已按当前钉钉身份进入本人盘点清单')
|
||||
} catch (error: any) {
|
||||
automaticIdentityError.value = error?.message || '当前钉钉账号不在本次盘点范围内'
|
||||
}
|
||||
await confirmBoundIdentity(request)
|
||||
} else if (!requiresDingTalkIdentity.value) {
|
||||
await searchParticipantsNow('')
|
||||
await searchParticipantsNow('', request)
|
||||
}
|
||||
}
|
||||
} catch (error: any) {
|
||||
setFeedback('error', error?.message || '获取盘点任务失败')
|
||||
if (taskScope.isCurrent(request)) setFeedback('error', error?.message || '获取盘点任务失败')
|
||||
} finally {
|
||||
loadingTask.value = false
|
||||
if (taskScope.isCurrent(request)) loadingTask.value = false
|
||||
}
|
||||
}
|
||||
|
||||
@ -755,114 +801,170 @@ const startDingTalkIdentityLogin = () => {
|
||||
window.location.assign(`/dingtalk-entry?redirect=${encodeURIComponent(redirect)}`)
|
||||
}
|
||||
|
||||
const confirmBoundIdentity = async (request = taskRequest) => {
|
||||
if (!usesBoundIdentity.value || confirmingParticipant.value) return
|
||||
confirmingParticipant.value = true
|
||||
automaticIdentityError.value = ''
|
||||
try {
|
||||
const response = await confirmCurrentInventoryParticipant(taskToken.value)
|
||||
if (!taskScope.isCurrent(request)) return
|
||||
const confirmed = await loadSessionAndItems(request, response.data.participant_id)
|
||||
if (!taskScope.isCurrent(request)) return
|
||||
if (!confirmed) {
|
||||
if (!identityNeedsConfirmation.value) throw new Error('钉钉身份已确认,但盘点会话建立失败')
|
||||
return
|
||||
}
|
||||
setFeedback('success', '已按当前钉钉身份进入本人盘点清单')
|
||||
} catch (error: any) {
|
||||
if (taskScope.isCurrent(request)) automaticIdentityError.value = error?.message || '当前钉钉账号不在本次盘点范围内'
|
||||
} finally {
|
||||
if (taskScope.isCurrent(request)) confirmingParticipant.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const confirmIdentity = async () => {
|
||||
if (!selectedParticipantId.value) {
|
||||
if (confirmingParticipant.value || loadingTask.value || session.value) return
|
||||
const participantId = selectedParticipantId.value
|
||||
if (!participantId) {
|
||||
setFeedback('error', '请先选择你的身份')
|
||||
return
|
||||
}
|
||||
|
||||
const request = taskRequest
|
||||
confirmingParticipant.value = true
|
||||
try {
|
||||
await confirmPublicInventoryParticipant(taskToken.value, selectedParticipantId.value)
|
||||
const hasSession = await loadSessionAndItems()
|
||||
const response = await confirmPublicInventoryParticipant(taskToken.value, participantId)
|
||||
if (!taskScope.isCurrent(request)) return
|
||||
const hasSession = await loadSessionAndItems(request, response.data.participant_id)
|
||||
if (!taskScope.isCurrent(request)) return
|
||||
if (!hasSession) {
|
||||
throw new Error('身份确认后未能建立盘点会话,请重试')
|
||||
if (!identityNeedsConfirmation.value) throw new Error('身份确认后未能建立盘点会话,请重试')
|
||||
return
|
||||
}
|
||||
setFeedback('success', '身份确认成功,现在可以开始盘点了')
|
||||
await nextTick()
|
||||
scanInputRef.value?.focus()
|
||||
if (taskScope.isCurrent(request)) scanInputRef.value?.focus()
|
||||
} catch (error: any) {
|
||||
setFeedback('error', error?.message || '确认身份失败')
|
||||
if (taskScope.isCurrent(request)) setFeedback('error', error?.message || '确认身份失败')
|
||||
} finally {
|
||||
confirmingParticipant.value = false
|
||||
if (taskScope.isCurrent(request)) confirmingParticipant.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const refreshAfterAction = async (handledItemId?: number) => {
|
||||
await loadTaskInfo()
|
||||
await loadSessionAndItems()
|
||||
if (handledItemId) {
|
||||
const refreshAfterAction = async (request: number, handledItemId: number) => {
|
||||
lastHandledItem.value = null
|
||||
try {
|
||||
await loadTaskInfo(request)
|
||||
if (!taskScope.isCurrent(request) || !await loadSessionAndItems(request)) return false
|
||||
if (!taskScope.isCurrent(request)) return false
|
||||
lastHandledItem.value = items.value.find((item) => item.id === handledItemId) || null
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
const submitCheckByCode = async (equipmentCode: string) => {
|
||||
const participantId = session.value?.participant.id
|
||||
if (actionLocked.value || !participantId) return
|
||||
if (isTaskClosed.value) {
|
||||
setFeedback('error', '盘点任务已关闭,不能继续提交结果')
|
||||
return
|
||||
}
|
||||
const normalizedCode = equipmentCode.trim()
|
||||
if (!normalizedCode) {
|
||||
setFeedback('error', '请输入资产编码')
|
||||
return
|
||||
}
|
||||
|
||||
const request = taskRequest
|
||||
const identity = { task_token: taskToken.value, participant_id: participantId }
|
||||
processingCode.value = normalizedCode
|
||||
try {
|
||||
const response = await submitPublicInventoryScan(normalizedCode)
|
||||
const response = await submitPublicInventoryScan(normalizedCode, identity)
|
||||
if (!taskScope.isCurrent(request)) return
|
||||
playBeepSound()
|
||||
scanCode.value = ''
|
||||
await refreshAfterAction(response.data.id)
|
||||
setFeedback('success', `已确认 ${response.data.equipment_name}`)
|
||||
await nextTick()
|
||||
scanInputRef.value?.focus()
|
||||
if (scanCode.value === normalizedCode) scanCode.value = ''
|
||||
const refreshed = await refreshAfterAction(request, response.data.id)
|
||||
if (!taskScope.isCurrent(request) || identityNeedsConfirmation.value) return
|
||||
const message = `已确认 ${response.data.equipment_name}`
|
||||
setFeedback(refreshed ? 'success' : 'info', refreshed ? message : `${message},但未能刷新清单,请重新加载页面。`)
|
||||
} catch (error: any) {
|
||||
if (!taskScope.isCurrent(request)) return
|
||||
if (isPublicInventorySessionChanged(error)) {
|
||||
await recoverIdentity(request)
|
||||
return
|
||||
}
|
||||
playErrorSound()
|
||||
setFeedback('error', error?.message || '提交盘点结果失败')
|
||||
} finally {
|
||||
processingCode.value = ''
|
||||
if (taskScope.isCurrent(request)) {
|
||||
processingCode.value = ''
|
||||
await nextTick()
|
||||
if (taskScope.isCurrent(request)) scanInputRef.value?.focus()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const handleSubmitScan = async () => {
|
||||
if (isTaskClosed.value) {
|
||||
setFeedback('error', '盘点任务已关闭,不能继续提交结果')
|
||||
return
|
||||
}
|
||||
await submitCheckByCode(scanCode.value)
|
||||
}
|
||||
const handleSubmitScan = () => submitCheckByCode(scanCode.value)
|
||||
|
||||
const handleCameraDetected = async (value: string) => {
|
||||
if (actionLocked.value || !session.value || isTaskClosed.value) return
|
||||
scanCode.value = value.trim()
|
||||
await handleSubmitScan()
|
||||
}
|
||||
|
||||
const markItemChecked = async (item: InventoryTaskItem) => {
|
||||
if (isTaskClosed.value) {
|
||||
setFeedback('error', '盘点任务已关闭,不能继续提交结果')
|
||||
return
|
||||
}
|
||||
await submitCheckByCode(item.equipment_code)
|
||||
const markItemChecked = (item: InventoryTaskItem) => {
|
||||
if (item.check_status === 'pending') return submitCheckByCode(item.equipment_code)
|
||||
}
|
||||
|
||||
const openExceptionModal = (item: InventoryTaskItem) => {
|
||||
if (actionLocked.value || !session.value || isTaskClosed.value) return
|
||||
exceptionTarget.value = item
|
||||
exceptionForm.exception_type = 'not_found'
|
||||
exceptionForm.exception_note = ''
|
||||
}
|
||||
|
||||
const closeExceptionModal = () => {
|
||||
if (exceptionSubmitting.value) return
|
||||
exceptionTarget.value = null
|
||||
exceptionForm.exception_type = 'not_found'
|
||||
exceptionForm.exception_note = ''
|
||||
}
|
||||
|
||||
const submitException = async () => {
|
||||
if (!exceptionTarget.value) return
|
||||
const target = exceptionTarget.value
|
||||
const participantId = session.value?.participant.id
|
||||
if (!target || submittingResult.value || loadingTask.value || !participantId || isTaskClosed.value) return
|
||||
const request = taskRequest
|
||||
const identity = { task_token: taskToken.value, participant_id: participantId }
|
||||
const payload = {
|
||||
exception_type: exceptionForm.exception_type,
|
||||
exception_note: exceptionForm.exception_note || undefined
|
||||
}
|
||||
|
||||
exceptionSubmitting.value = true
|
||||
try {
|
||||
await submitPublicInventoryException(exceptionTarget.value.id, {
|
||||
exception_type: exceptionForm.exception_type,
|
||||
exception_note: exceptionForm.exception_note || undefined
|
||||
})
|
||||
await refreshAfterAction(exceptionTarget.value.id)
|
||||
setFeedback('success', `已为 ${exceptionTarget.value.equipment_name} 提交异常`)
|
||||
closeExceptionModal()
|
||||
await submitPublicInventoryException(target.id, payload, identity)
|
||||
if (!taskScope.isCurrent(request)) return
|
||||
const refreshed = await refreshAfterAction(request, target.id)
|
||||
if (!taskScope.isCurrent(request) || identityNeedsConfirmation.value) return
|
||||
const message = `已为 ${target.equipment_name} 提交异常`
|
||||
setFeedback(refreshed ? 'success' : 'info', refreshed ? message : `${message},但未能刷新清单,请重新加载页面。`)
|
||||
exceptionTarget.value = null
|
||||
} catch (error: any) {
|
||||
setFeedback('error', error?.message || '提交盘点异常失败')
|
||||
if (!taskScope.isCurrent(request)) return
|
||||
if (isPublicInventorySessionChanged(error)) await recoverIdentity(request)
|
||||
else setFeedback('error', error?.message || '提交盘点异常失败')
|
||||
} finally {
|
||||
exceptionSubmitting.value = false
|
||||
if (taskScope.isCurrent(request)) exceptionSubmitting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const switchIdentity = async () => {
|
||||
if (actionLocked.value) return
|
||||
showCameraScanner.value = false
|
||||
scanCode.value = ''
|
||||
resetSessionState()
|
||||
selectedParticipantId.value = null
|
||||
setFeedback('info', '你可以重新选择自己的身份。')
|
||||
@ -893,6 +995,7 @@ onMounted(() => {
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
taskScope.dispose()
|
||||
if (participantSearchTimer) {
|
||||
window.clearTimeout(participantSearchTimer)
|
||||
}
|
||||
|
||||
@ -13,7 +13,7 @@
|
||||
<p class="page-meta__subvalue">系统留痕</p>
|
||||
</div>
|
||||
<div class="page-meta" style="min-width: 120px;">
|
||||
<p class="page-meta__label">待处理</p>
|
||||
<p class="page-meta__label">未查看</p>
|
||||
<p class="page-meta__value" :class="notificationStore.unreadCount > 0 ? 'text-status-warning' : ''">
|
||||
{{ notificationStore.unreadCount }}
|
||||
</p>
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
<template>
|
||||
<div class="space-y-6">
|
||||
<section class="card !p-3">
|
||||
<div class="overflow-x-auto scroll-smooth">
|
||||
<nav class="overflow-x-auto scroll-smooth" aria-label="系统设置">
|
||||
<div class="segmented-toggle min-w-max" style="padding: 2px;">
|
||||
<button
|
||||
v-for="tab in tabs"
|
||||
@ -12,12 +12,13 @@
|
||||
class="segmented-toggle__item"
|
||||
style="min-height: 32px; padding: 0 12px; font-size: 12px;"
|
||||
:class="{ 'is-active': activeTab === tab.key }"
|
||||
:aria-current="activeTab === tab.key ? 'page' : undefined"
|
||||
@click="switchTab(tab.key)"
|
||||
>
|
||||
{{ tab.label }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
</section>
|
||||
|
||||
<div class="min-h-[400px]">
|
||||
|
||||
@ -5,6 +5,7 @@
|
||||
<div>
|
||||
<p class="page-kicker">Disposal</p>
|
||||
<h2 class="page-title">报废流程</h2>
|
||||
<slot name="actions" />
|
||||
</div>
|
||||
<div class="page-meta-grid">
|
||||
<div class="page-meta">
|
||||
@ -145,22 +146,22 @@
|
||||
|
||||
<div class="mt-4 flex gap-2">
|
||||
<button
|
||||
v-if="item.status === 'pending' && canApproveItem(item)"
|
||||
v-if="item.status === 'pending' && canApprove"
|
||||
class="btn-primary text-xs sm:text-sm"
|
||||
@click="handleApprove(item, true)"
|
||||
@click="openDetail(item)"
|
||||
>
|
||||
通过
|
||||
核对审批
|
||||
</button>
|
||||
<button
|
||||
v-else-if="item.status === 'approved' && canComplete"
|
||||
class="btn-primary text-xs sm:text-sm"
|
||||
@click="handleComplete(item)"
|
||||
@click="openDetail(item)"
|
||||
>
|
||||
完成
|
||||
核对处置
|
||||
</button>
|
||||
<button v-else class="btn-secondary text-xs sm:text-sm" @click="openDetail(item)">查看详情</button>
|
||||
<button
|
||||
v-if="hasMobileSecondaryActions(item)"
|
||||
v-if="item.status === 'pending' && canApprove"
|
||||
class="btn-secondary text-xs sm:text-sm"
|
||||
@click="mobileActionItem = item"
|
||||
>
|
||||
@ -212,28 +213,28 @@
|
||||
<td class="text-sm text-text-secondary">{{ formatDate(item.applied_at) }}</td>
|
||||
<td class="text-right">
|
||||
<div class="table-action-group justify-end">
|
||||
<button class="table-action" @click="openDetail(item)">详情</button>
|
||||
<button
|
||||
v-if="item.status === 'pending' && canApproveItem(item)"
|
||||
v-if="item.status === 'pending' && canApprove"
|
||||
class="table-action table-action--primary"
|
||||
@click="handleApprove(item, true)"
|
||||
@click="openDetail(item)"
|
||||
>
|
||||
通过
|
||||
核对审批
|
||||
</button>
|
||||
<button
|
||||
v-if="item.status === 'pending' && canApproveItem(item)"
|
||||
v-else-if="item.status === 'approved' && canComplete"
|
||||
class="table-action table-action--warning"
|
||||
@click="openDetail(item)"
|
||||
>
|
||||
核对处置
|
||||
</button>
|
||||
<button v-else class="table-action" @click="openDetail(item)">详情</button>
|
||||
<button
|
||||
v-if="item.status === 'pending' && canApprove"
|
||||
class="table-action table-action--danger"
|
||||
@click="handleApprove(item, false)"
|
||||
@click="handleReject(item)"
|
||||
>
|
||||
驳回
|
||||
</button>
|
||||
<button
|
||||
v-if="item.status === 'approved' && canComplete"
|
||||
class="table-action table-action--warning"
|
||||
@click="handleComplete(item)"
|
||||
>
|
||||
完成
|
||||
</button>
|
||||
<span v-if="item.status === 'completed'" class="text-sm text-text-tertiary">已完成</span>
|
||||
<span v-if="item.status === 'rejected'" class="text-sm text-text-tertiary">已驳回</span>
|
||||
</div>
|
||||
@ -266,7 +267,7 @@
|
||||
>
|
||||
<button type="button" class="btn-secondary w-full" @click="handleMobileOpenDetail">查看详情</button>
|
||||
<button
|
||||
v-if="mobileActionItem?.status === 'pending' && canApproveItem(mobileActionItem)"
|
||||
v-if="mobileActionItem?.status === 'pending' && canApprove"
|
||||
type="button"
|
||||
class="btn-secondary w-full !text-status-error"
|
||||
@click="handleMobileReject"
|
||||
@ -275,43 +276,6 @@
|
||||
</button>
|
||||
</MobileActionSheet>
|
||||
|
||||
<!-- 完成处置弹窗 -->
|
||||
<div v-if="showCompleteModal" class="sheet-backdrop">
|
||||
<div class="sheet-panel max-w-2xl">
|
||||
<h3 class="text-xl font-semibold text-text-primary mb-4">完成处置</h3>
|
||||
<p class="text-sm text-text-secondary mb-4">
|
||||
{{ currentItem?.equipment?.equipment_name || currentItem?.equipment_code || '当前资产' }} 已通过审批,请补充最终处置结果。
|
||||
</p>
|
||||
|
||||
<div class="field-grid">
|
||||
<div class="field-stack">
|
||||
<label class="field-label">实际处置价值</label>
|
||||
<input v-model.number="completeForm.actual_value" type="number" min="0" step="0.01" class="input" />
|
||||
</div>
|
||||
<div class="panel">
|
||||
<p class="text-xs text-text-tertiary">残值估价</p>
|
||||
<p class="mt-1 text-base font-medium text-text-primary">{{ formatCurrency(currentItem?.estimated_value || 0) }}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mt-4 field-stack">
|
||||
<label class="field-label">完成说明 *</label>
|
||||
<textarea
|
||||
v-model.trim="completeForm.completion_notes"
|
||||
class="input"
|
||||
rows="4"
|
||||
placeholder="例如:已转交回收商,回收凭证已登记"
|
||||
></textarea>
|
||||
</div>
|
||||
|
||||
<div class="flex justify-end gap-3 mt-6">
|
||||
<button class="btn-secondary" @click="showCompleteModal = false">取消</button>
|
||||
<button class="btn-primary" :disabled="submittingComplete || !completeForm.completion_notes" @click="submitComplete">
|
||||
{{ submittingComplete ? '提交中...' : '确认完成' }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@ -321,13 +285,13 @@ import { useRoute, useRouter } from 'vue-router'
|
||||
import {
|
||||
getDisposalList,
|
||||
approveDisposal,
|
||||
completeDisposal,
|
||||
type DisposalRecord,
|
||||
type DisposalSummary
|
||||
} from '@/api/disposal'
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
import { PERMISSIONS } from '@/auth/permissions'
|
||||
import MobileActionSheet from '@/components/MobileActionSheet.vue'
|
||||
import { createRequestScope } from '@/utils/requestScope'
|
||||
|
||||
type DisposalScope = 'pending' | 'mine' | 'processed' | 'all'
|
||||
|
||||
@ -355,32 +319,32 @@ const loading = ref(false)
|
||||
const listError = ref('')
|
||||
const summary = ref<DisposalSummary | null>(null)
|
||||
const filters = ref({ status: '', keyword: '' })
|
||||
const showCompleteModal = ref(false)
|
||||
const currentItem = ref<DisposalRecord | null>(null)
|
||||
const completeForm = ref({ actual_value: 0, completion_notes: '' })
|
||||
const submittingComplete = ref(false)
|
||||
const activeScope = ref<DisposalScope>('pending')
|
||||
const mobileActionItem = ref<DisposalRecord | null>(null)
|
||||
|
||||
let searchTimer: ReturnType<typeof setTimeout> | null = null
|
||||
const listScope = createRequestScope()
|
||||
|
||||
const totalPages = computed(() => Math.max(1, Math.ceil(total.value / pageSize.value)))
|
||||
const loadList = async () => {
|
||||
const request = listScope.begin()
|
||||
loading.value = true
|
||||
listError.value = ''
|
||||
try {
|
||||
const res = await getDisposalList({ page: page.value, pageSize: pageSize.value, scope: activeScope.value, ...filters.value })
|
||||
if (!listScope.isCurrent(request)) return
|
||||
list.value = res.data?.list || []
|
||||
total.value = res.data?.total || 0
|
||||
summary.value = res.data?.summary || null
|
||||
} catch (e: any) {
|
||||
if (!listScope.isCurrent(request)) return
|
||||
console.error(e)
|
||||
list.value = []
|
||||
total.value = 0
|
||||
summary.value = null
|
||||
listError.value = e?.message || '报废记录加载失败,请稍后重试。'
|
||||
} finally {
|
||||
loading.value = false
|
||||
if (listScope.isCurrent(request)) loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
@ -407,16 +371,22 @@ const changeScope = (scope: DisposalScope) => {
|
||||
activeScope.value = scope
|
||||
page.value = 1
|
||||
router.replace({ query: { ...route.query, scope } })
|
||||
loadList()
|
||||
return loadList()
|
||||
}
|
||||
|
||||
const showOwnApplications = () => {
|
||||
if (searchTimer) {
|
||||
clearTimeout(searchTimer)
|
||||
searchTimer = null
|
||||
}
|
||||
filters.value = { status: '', keyword: '' }
|
||||
return changeScope('mine')
|
||||
}
|
||||
|
||||
defineExpose({ showOwnApplications })
|
||||
|
||||
const openDetail = (item: DisposalRecord) => router.push(`/workflows/disposals/${item.id}`)
|
||||
|
||||
const hasMobileSecondaryActions = (item: DisposalRecord) =>
|
||||
(item.status === 'pending' && canApproveItem(item)) || (item.status === 'approved' && canComplete.value)
|
||||
|
||||
const canApproveItem = (_item: DisposalRecord) => canApprove.value
|
||||
|
||||
const handleMobileOpenDetail = () => {
|
||||
const item = mobileActionItem.value
|
||||
mobileActionItem.value = null
|
||||
@ -426,19 +396,18 @@ const handleMobileOpenDetail = () => {
|
||||
const handleMobileReject = async () => {
|
||||
const item = mobileActionItem.value
|
||||
mobileActionItem.value = null
|
||||
if (item) await handleApprove(item, false)
|
||||
if (item) await handleReject(item)
|
||||
}
|
||||
|
||||
const handleApprove = async (item: DisposalRecord, approved: boolean) => {
|
||||
const msg = approved ? '确定通过此报废申请吗?' : '确定驳回此报废申请吗?'
|
||||
if (!confirm(msg)) return
|
||||
const handleReject = async (item: DisposalRecord) => {
|
||||
if (!confirm('确定驳回此报废申请吗?')) return
|
||||
try {
|
||||
const rejectReason = approved ? undefined : window.prompt('请填写驳回原因。', '')?.trim() || undefined
|
||||
if (!approved && !rejectReason) {
|
||||
const rejectReason = window.prompt('请填写驳回原因。', '')?.trim()
|
||||
if (!rejectReason) {
|
||||
alert('驳回原因不能为空')
|
||||
return
|
||||
}
|
||||
await approveDisposal(item.id, { approved, reject_reason: rejectReason })
|
||||
await approveDisposal(item.id, { approved: false, reject_reason: rejectReason })
|
||||
await loadList()
|
||||
} catch (error: any) {
|
||||
alert(error?.message || '申请状态已变化,请刷新后重试')
|
||||
@ -446,27 +415,6 @@ const handleApprove = async (item: DisposalRecord, approved: boolean) => {
|
||||
}
|
||||
}
|
||||
|
||||
const handleComplete = (item: DisposalRecord) => {
|
||||
currentItem.value = item
|
||||
completeForm.value = { actual_value: Number(item.estimated_value || 0), completion_notes: item.completion_notes || '' }
|
||||
showCompleteModal.value = true
|
||||
}
|
||||
|
||||
const submitComplete = async () => {
|
||||
if (!currentItem.value || !completeForm.value.completion_notes.trim()) return
|
||||
try {
|
||||
submittingComplete.value = true
|
||||
await completeDisposal(currentItem.value.id, completeForm.value)
|
||||
showCompleteModal.value = false
|
||||
await loadList()
|
||||
} catch (error: any) {
|
||||
alert(error?.message || '申请状态已变化,请刷新后重试')
|
||||
await loadList()
|
||||
} finally {
|
||||
submittingComplete.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const handlePrevPage = async () => {
|
||||
if (page.value <= 1) return
|
||||
page.value -= 1
|
||||
@ -518,5 +466,6 @@ onMounted(() => {
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
if (searchTimer) clearTimeout(searchTimer)
|
||||
listScope.dispose()
|
||||
})
|
||||
</script>
|
||||
|
||||
@ -351,7 +351,6 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, reactive, ref } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import * as XLSX from 'xlsx'
|
||||
import type { Person } from '@/types'
|
||||
import { createPerson, getPersonList, updatePerson, updatePersonStatus, deletePerson } from '@/api/person'
|
||||
import { batchImportPersons } from '@/api/batchImport'
|
||||
@ -670,10 +669,11 @@ const parseFileContent = async (file: File): Promise<string[][]> => {
|
||||
const ext = file.name.split('.').pop()?.toLowerCase()
|
||||
|
||||
if (ext === 'xlsx' || ext === 'xls') {
|
||||
const workbook = XLSX.read(buffer, { type: 'array' })
|
||||
const { read, utils } = await import('xlsx')
|
||||
const workbook = read(buffer, { type: 'array' })
|
||||
const sheetName = workbook.SheetNames[0]
|
||||
const sheet = workbook.Sheets[sheetName]
|
||||
return XLSX.utils.sheet_to_json<string[]>(sheet, { header: 1 })
|
||||
return utils.sheet_to_json<string[]>(sheet, { header: 1 })
|
||||
}
|
||||
|
||||
const bytes = new Uint8Array(buffer)
|
||||
|
||||
@ -74,12 +74,15 @@
|
||||
|
||||
<!-- 图表 -->
|
||||
<div v-if="statistics" class="grid gap-6 lg:grid-cols-2">
|
||||
<p v-if="chartError" class="panel text-sm text-text-secondary lg:col-span-2" role="status">
|
||||
图表暂时无法显示,仍可查看统计数字。
|
||||
</p>
|
||||
<section class="card">
|
||||
<div class="list-header">
|
||||
<h3 class="section-title">价值结构占比</h3>
|
||||
<span class="badge badge-neutral">价值口径</span>
|
||||
</div>
|
||||
<div ref="valueChartRef" class="h-80"></div>
|
||||
<div v-show="!chartError" ref="valueChartRef" class="h-80"></div>
|
||||
</section>
|
||||
|
||||
<section class="card">
|
||||
@ -87,7 +90,7 @@
|
||||
<h3 class="section-title">按类型的价值结构</h3>
|
||||
<span class="badge badge-neutral">总值 / 借出 / 可用</span>
|
||||
</div>
|
||||
<div ref="typeChartRef" class="h-80"></div>
|
||||
<div v-show="!chartError" ref="typeChartRef" class="h-80"></div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
@ -173,16 +176,18 @@
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onMounted, onUnmounted, reactive, ref } from 'vue'
|
||||
import * as echarts from 'echarts'
|
||||
import type { EChartsType } from 'echarts/core'
|
||||
import { getValueStatistics } from '@/api/statistics'
|
||||
import { getAssetTypeOptions } from '@/api/assetType'
|
||||
import type { AssetType, ValueStatistics } from '@/types'
|
||||
import { formatCurrencyNoFraction } from '@/utils/format'
|
||||
import { createRequestScope } from '@/utils/requestScope'
|
||||
|
||||
const valueChartRef = ref<HTMLElement>()
|
||||
const typeChartRef = ref<HTMLElement>()
|
||||
const loading = ref(false)
|
||||
const statisticsError = ref('')
|
||||
const chartError = ref(false)
|
||||
const assetTypes = ref<AssetType[]>([])
|
||||
const statistics = ref<ValueStatistics | null>(null)
|
||||
|
||||
@ -192,8 +197,9 @@ const filters = reactive({
|
||||
end_date: ''
|
||||
})
|
||||
|
||||
let valueChart: echarts.ECharts | null = null
|
||||
let typeChart: echarts.ECharts | null = null
|
||||
let valueChart: EChartsType | null = null
|
||||
let typeChart: EChartsType | null = null
|
||||
const statisticsRequests = createRequestScope()
|
||||
|
||||
const summary = computed(() => ({
|
||||
total_value: statistics.value?.total_value || 0,
|
||||
@ -219,22 +225,31 @@ const fetchAssetTypes = async () => {
|
||||
}
|
||||
|
||||
const fetchStatistics = async () => {
|
||||
const request = statisticsRequests.begin()
|
||||
loading.value = true
|
||||
statisticsError.value = ''
|
||||
chartError.value = false
|
||||
try {
|
||||
const response = await getValueStatistics({
|
||||
equipment_type: filters.equipment_type || undefined,
|
||||
start_date: filters.start_date || undefined,
|
||||
end_date: filters.end_date || undefined
|
||||
})
|
||||
if (response.data) {
|
||||
statistics.value = response.data
|
||||
await nextTick()
|
||||
initCharts(response.data)
|
||||
} else {
|
||||
throw new Error('价值统计接口未返回数据')
|
||||
if (!statisticsRequests.isCurrent(request)) return
|
||||
if (!response.data) throw new Error('价值统计接口未返回数据')
|
||||
statistics.value = response.data
|
||||
await nextTick()
|
||||
try {
|
||||
const { init } = await import('@/utils/assetCharts')
|
||||
if (!statisticsRequests.isCurrent(request) || !valueChartRef.value || !typeChartRef.value) return
|
||||
valueChart ??= init(valueChartRef.value)
|
||||
typeChart ??= init(typeChartRef.value)
|
||||
updateCharts(response.data)
|
||||
} catch {
|
||||
if (statisticsRequests.isCurrent(request)) chartError.value = true
|
||||
}
|
||||
} catch (error) {
|
||||
if (!statisticsRequests.isCurrent(request)) return
|
||||
console.error('获取统计数据失败:', error)
|
||||
statistics.value = null
|
||||
statisticsError.value = '价值统计读取失败'
|
||||
@ -243,18 +258,11 @@ const fetchStatistics = async () => {
|
||||
valueChart = null
|
||||
typeChart = null
|
||||
} finally {
|
||||
loading.value = false
|
||||
if (statisticsRequests.isCurrent(request)) loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const initCharts = (data: ValueStatistics) => {
|
||||
if (valueChartRef.value && !valueChart) {
|
||||
valueChart = echarts.init(valueChartRef.value)
|
||||
}
|
||||
if (typeChartRef.value && !typeChart) {
|
||||
typeChart = echarts.init(typeChartRef.value)
|
||||
}
|
||||
|
||||
const updateCharts = (data: ValueStatistics) => {
|
||||
// 深色主题配色
|
||||
const darkColors = {
|
||||
available: '#10b981', // status-success
|
||||
@ -379,11 +387,12 @@ const resizeHandler = () => {
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
await Promise.all([fetchAssetTypes(), fetchStatistics()])
|
||||
window.addEventListener('resize', resizeHandler)
|
||||
await Promise.all([fetchAssetTypes(), fetchStatistics()])
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
statisticsRequests.dispose()
|
||||
valueChart?.dispose()
|
||||
typeChart?.dispose()
|
||||
window.removeEventListener('resize', resizeHandler)
|
||||
|
||||
@ -13,7 +13,10 @@
|
||||
</div>
|
||||
<div class="page-meta">
|
||||
<p class="page-meta__label">包含资产</p>
|
||||
<p class="page-meta__value">{{ record.items?.length || 1 }}</p>
|
||||
<p class="page-meta__value">{{ disposalItems.length }} 项</p>
|
||||
<p v-if="disposalQuantity !== null" class="page-meta__subvalue">
|
||||
{{ needsApprovedQuantityCheck ? '当前台账' : '合计' }} {{ disposalQuantity }} 件
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
@ -69,13 +72,16 @@
|
||||
<span class="badge badge-neutral">申请后关系已锁定</span>
|
||||
</div>
|
||||
<div class="space-y-3">
|
||||
<div v-for="(item, index) in disposalItems" :key="item.id || item.equipment_id" class="panel flex items-center justify-between gap-4">
|
||||
<div v-for="({ item, quantity, fromSnapshot }, index) in disposalItems" :key="item.id || item.equipment_id" class="panel flex items-center justify-between gap-4">
|
||||
<div class="min-w-0">
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<span v-if="item.is_root || item.parent_equipment_id == null || index === 0" class="badge badge-neutral">主资产</span>
|
||||
<p class="truncate text-sm font-medium text-text-primary">{{ getItemName(item) }}</p>
|
||||
</div>
|
||||
<p class="mt-1 font-mono text-xs text-text-tertiary">{{ item.equipment_code || item.equipment?.equipment_code }}</p>
|
||||
<p class="mt-1 text-sm text-text-secondary">
|
||||
{{ quantity === null ? '数量待核对' : fromSnapshot ? `申请数量 ${quantity} 件` : `当前数量 ${quantity} 件` }}
|
||||
</p>
|
||||
</div>
|
||||
<div class="text-right">
|
||||
<p class="text-xs text-text-tertiary">申请前状态</p>
|
||||
@ -105,13 +111,38 @@
|
||||
<section v-if="showActions" class="card">
|
||||
<h3 class="section-title">处理申请</h3>
|
||||
<div v-if="record.status === 'pending' && canApproveRecord" class="mt-4 grid gap-4 md:grid-cols-2">
|
||||
<button type="button" class="btn-primary" :disabled="submitting" @click="submitApproval(true)">审批通过</button>
|
||||
<div class="field-stack">
|
||||
<p v-if="disposalQuantity === null" class="text-sm text-status-warning">
|
||||
部分资产缺少可核对的数量,请重新加载后核对明细。
|
||||
</p>
|
||||
<p v-else class="text-sm text-text-secondary">
|
||||
本单申请处置 {{ disposalQuantity }} 件。
|
||||
<template v-if="hasCurrentQuantities">旧单明细所列的当前数量将在通过时记入审批。</template>
|
||||
</p>
|
||||
<button type="button" class="btn-primary" :disabled="submitting || disposalQuantity === null" @click="submitApproval(true)">
|
||||
审批通过
|
||||
</button>
|
||||
</div>
|
||||
<div class="field-stack">
|
||||
<label class="field-label">驳回原因</label>
|
||||
<textarea v-model.trim="rejectReason" class="input" rows="3" placeholder="驳回时必须填写原因"></textarea>
|
||||
<button type="button" class="btn-secondary !text-status-error" :disabled="submitting || !rejectReason" @click="submitApproval(false)">确认驳回</button>
|
||||
</div>
|
||||
</div>
|
||||
<div v-else-if="needsApprovedQuantityCheck" class="mt-4 space-y-4">
|
||||
<p class="text-sm text-status-warning">
|
||||
旧单缺少完整的审批数量。请按原审批材料逐项核对,确认数量后才能完成处置。
|
||||
</p>
|
||||
<button
|
||||
v-if="canApprove"
|
||||
type="button"
|
||||
class="btn-primary"
|
||||
:disabled="submitting || disposalQuantity === null"
|
||||
@click="submitApproval(true, true)"
|
||||
>
|
||||
确认旧单数量
|
||||
</button>
|
||||
</div>
|
||||
<div v-else-if="record.status === 'approved' && canComplete" class="mt-4 space-y-4">
|
||||
<div class="field-grid">
|
||||
<div class="field-stack">
|
||||
@ -139,6 +170,7 @@ import {
|
||||
approveDisposal,
|
||||
completeDisposal,
|
||||
getDisposalDetail,
|
||||
type ConfirmedDisposalQuantity,
|
||||
type DisposalAction,
|
||||
type DisposalItem,
|
||||
type DisposalRecord
|
||||
@ -160,23 +192,54 @@ 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 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)
|
||||
(record.value?.status === 'approved' && (canComplete.value || (needsApprovedQuantityCheck.value && canApprove.value)))
|
||||
)
|
||||
const disposalItems = computed<DisposalItem[]>(() => {
|
||||
if (record.value?.items?.length) return record.value.items
|
||||
if (!record.value) return []
|
||||
return [{
|
||||
id: record.value.id,
|
||||
equipment_id: record.value.equipment_id,
|
||||
equipment_code: record.value.equipment_code,
|
||||
equipment_name: record.value.equipment?.equipment_name,
|
||||
equipment_type: record.value.equipment?.equipment_type,
|
||||
pre_status: record.value.pre_status,
|
||||
const parseQuantity = (value: unknown): number | null =>
|
||||
typeof value === 'number' && Number.isSafeInteger(value) && value > 0 ? value : null
|
||||
|
||||
const disposalItems = computed(() => {
|
||||
const current = record.value
|
||||
if (!current) return []
|
||||
const items: DisposalItem[] = current.items?.length ? current.items : [{
|
||||
id: current.id,
|
||||
equipment_id: current.equipment_id,
|
||||
equipment_code: current.equipment_code,
|
||||
equipment: current.equipment,
|
||||
pre_status: current.pre_status,
|
||||
is_root: true
|
||||
}]
|
||||
return items.map((item) => {
|
||||
try {
|
||||
const snapshot = item.snapshot_json ? JSON.parse(item.snapshot_json) : {}
|
||||
if (snapshot.total_quantity !== undefined) {
|
||||
return { item, quantity: parseQuantity(snapshot.total_quantity), fromSnapshot: true }
|
||||
}
|
||||
} catch {
|
||||
return { item, quantity: null, fromSnapshot: false }
|
||||
}
|
||||
const quantity = current.status === 'pending' || needsApprovedQuantityCheck.value
|
||||
? parseQuantity(item.equipment?.total_quantity)
|
||||
: null
|
||||
return { item, quantity, fromSnapshot: false }
|
||||
})
|
||||
})
|
||||
const confirmedQuantities = computed(() => {
|
||||
const quantities: ConfirmedDisposalQuantity[] = []
|
||||
for (const { item, quantity } of disposalItems.value) {
|
||||
if (quantity === null) return null
|
||||
quantities.push({ equipment_id: item.equipment_id, total_quantity: quantity })
|
||||
}
|
||||
return quantities.length ? quantities : null
|
||||
})
|
||||
const disposalQuantity = computed(() =>
|
||||
confirmedQuantities.value?.reduce((sum, item) => sum + item.total_quantity, 0) ?? null
|
||||
)
|
||||
const hasCurrentQuantities = computed(() => disposalItems.value.some((entry) => !entry.fromSnapshot && entry.quantity !== null))
|
||||
|
||||
const loadDetail = async () => {
|
||||
loading.value = true
|
||||
@ -193,13 +256,24 @@ const loadDetail = async () => {
|
||||
}
|
||||
}
|
||||
|
||||
const submitApproval = async (approved: boolean) => {
|
||||
if (!record.value) return
|
||||
const submitApproval = async (approved: boolean, reconfirm = false) => {
|
||||
const quantities = confirmedQuantities.value
|
||||
if (!record.value || submitting.value || (approved && !quantities)) return
|
||||
if (!approved && !rejectReason.value) return
|
||||
if (!confirm(approved ? '确定审批通过此报废申请吗?' : '确定驳回此报废申请吗?')) return
|
||||
const message = reconfirm
|
||||
? `已按原审批材料核对明细中的 ${disposalQuantity.value} 件资产,确认记录该数量?`
|
||||
: approved
|
||||
? `确认批准处置明细中的 ${disposalQuantity.value} 件资产?`
|
||||
: '确定驳回此报废申请吗?'
|
||||
if (!confirm(message)) return
|
||||
submitting.value = true
|
||||
try {
|
||||
await approveDisposal(record.value.id, { approved, reject_reason: approved ? undefined : rejectReason.value })
|
||||
await approveDisposal(record.value.id, {
|
||||
approved,
|
||||
reject_reason: approved ? undefined : rejectReason.value,
|
||||
confirmed_quantities: approved ? quantities ?? undefined : undefined,
|
||||
reconfirm_quantities: reconfirm || undefined
|
||||
})
|
||||
await loadDetail()
|
||||
} catch (error: any) {
|
||||
alert(error?.message || '申请状态已变化,请刷新后重试')
|
||||
@ -210,7 +284,9 @@ const submitApproval = async (approved: boolean) => {
|
||||
}
|
||||
|
||||
const submitCompletion = async () => {
|
||||
if (!record.value || !completeForm.value.completion_notes.trim() || !confirm('确定所有明细资产均已完成处置吗?')) return
|
||||
if (!record.value || submitting.value || needsApprovedQuantityCheck.value || !completeForm.value.completion_notes.trim()) return
|
||||
const count = disposalQuantity.value
|
||||
if (!confirm(count === null ? '确定所有明细资产均已完成处置吗?' : `确认明细中的 ${count} 件资产均已完成处置?`)) return
|
||||
submitting.value = true
|
||||
try {
|
||||
await completeDisposal(record.value.id, completeForm.value)
|
||||
@ -233,6 +309,7 @@ const getActionText = (action: DisposalAction) => {
|
||||
submitted: '提交报废申请',
|
||||
approve: '审批通过',
|
||||
approved: '审批通过',
|
||||
quantity_confirmed: '复核旧单审批数量',
|
||||
reject: '驳回申请',
|
||||
rejected: '驳回申请',
|
||||
complete: '完成报废',
|
||||
|
||||
@ -1,7 +1,40 @@
|
||||
<template>
|
||||
<DisposalManagement />
|
||||
<DisposalManagement ref="management">
|
||||
<template #actions>
|
||||
<div v-if="canApply" class="mt-3 flex flex-wrap gap-2">
|
||||
<button type="button" class="btn-primary text-sm" @click="launchMode = 'pick'">发起报废申请</button>
|
||||
<button type="button" class="btn-secondary text-sm" @click="launchMode = 'import'">导入报废清单</button>
|
||||
</div>
|
||||
<p v-if="submittedCount !== null" class="mt-2 text-sm text-status-success" role="status">
|
||||
已提交 {{ submittedCount }} 项报废申请,等待审批。
|
||||
</p>
|
||||
</template>
|
||||
</DisposalManagement>
|
||||
<BatchDisposalDialog
|
||||
v-if="canApply && launchMode"
|
||||
:equipment-ids="[]"
|
||||
:pick-assets="launchMode === 'pick'"
|
||||
@close="launchMode = null"
|
||||
@submitted="handleSubmitted"
|
||||
/>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, ref } from 'vue'
|
||||
import { PERMISSIONS } from '@/auth/permissions'
|
||||
import BatchDisposalDialog from '@/components/BatchDisposalDialog.vue'
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
import DisposalManagement from '@/views/settings/components/DisposalManagement.vue'
|
||||
|
||||
const authStore = useAuthStore()
|
||||
const canApply = computed(() => authStore.can(PERMISSIONS.DISPOSALS_APPLY))
|
||||
const management = ref<InstanceType<typeof DisposalManagement> | null>(null)
|
||||
const launchMode = ref<'pick' | 'import' | null>(null)
|
||||
const submittedCount = ref<number | null>(null)
|
||||
|
||||
const handleSubmitted = (result: { count: number }) => {
|
||||
launchMode.value = null
|
||||
submittedCount.value = result.count
|
||||
void management.value?.showOwnApplications()
|
||||
}
|
||||
</script>
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user