From 9d1f065927cbe8c4a76938b8947f24d6aa65ca58 Mon Sep 17 00:00:00 2001 From: WuYongJie Date: Tue, 10 Nov 2026 15:41:30 +0800 Subject: [PATCH] feat: start asset disposal from the workflow page --- ...assetWorkflowIntegrity.integration.test.ts | 290 +++++++++++++++ .../disposalBatch.integration.test.ts | 9 +- .../disposalController.state-machine.test.ts | 14 +- .../disposalController.visibility.test.ts | 2 +- .../equipmentController.update-status.test.ts | 17 +- backend/src/controllers/disposalController.ts | 173 +++++++-- .../src/controllers/equipmentController.ts | 65 ++-- .../src/controllers/inventoryController.ts | 2 +- .../controllers/publicInventoryController.ts | 64 ++-- .../__tests__/inventoryIdentity.test.ts | 1 + backend/src/services/assetMovementService.ts | 15 +- backend/src/services/inventoryService.ts | 15 +- backend/src/utils/disposalSubmission.ts | 2 + frontend/scripts/test-borrow-person-search.ts | 2 +- frontend/scripts/test-scan-request-order.mjs | 339 ++++++++++++++++++ frontend/src/api/disposal.ts | 20 +- frontend/src/api/publicInventory.ts | 36 +- .../src/components/BatchDisposalDialog.vue | 132 +++++-- .../src/components/DisposalAssetPicker.vue | 130 +++++++ frontend/src/layouts/MainLayout.vue | 112 ++++-- frontend/src/style.css | 2 +- frontend/src/utils/assetCharts.ts | 8 + frontend/src/utils/dialogFocus.ts | 20 ++ frontend/src/views/Login.vue | 59 ++- frontend/src/views/borrow/BorrowList.vue | 53 ++- frontend/src/views/borrow/BorrowScan.vue | 151 ++++---- frontend/src/views/borrow/ReturnScan.vue | 224 ++++++------ frontend/src/views/dashboard/Dashboard.vue | 47 ++- .../src/views/equipment/EquipmentList.vue | 60 +++- .../views/inventory/PublicInventoryTask.vue | 271 +++++++++----- .../notifications/NotificationCenter.vue | 2 +- frontend/src/views/settings/Settings.vue | 5 +- .../components/DisposalManagement.vue | 143 +++----- .../settings/components/PersonManagement.vue | 6 +- frontend/src/views/statistics/Statistics.vue | 51 +-- .../src/views/workflows/DisposalDetail.vue | 115 +++++- frontend/src/views/workflows/DisposalList.vue | 35 +- 37 files changed, 2049 insertions(+), 643 deletions(-) create mode 100644 backend/src/controllers/__tests__/assetWorkflowIntegrity.integration.test.ts create mode 100644 frontend/scripts/test-scan-request-order.mjs create mode 100644 frontend/src/components/DisposalAssetPicker.vue create mode 100644 frontend/src/utils/assetCharts.ts create mode 100644 frontend/src/utils/dialogFocus.ts diff --git a/backend/src/controllers/__tests__/assetWorkflowIntegrity.integration.test.ts b/backend/src/controllers/__tests__/assetWorkflowIntegrity.integration.test.ts new file mode 100644 index 0000000..17dced9 --- /dev/null +++ b/backend/src/controllers/__tests__/assetWorkflowIntegrity.integration.test.ts @@ -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 = {}, session?: object, query?: Record) => { + 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() + } + } +}) diff --git a/backend/src/controllers/__tests__/disposalBatch.integration.test.ts b/backend/src/controllers/__tests__/disposalBatch.integration.test.ts index 86333ef..7cc0034 100644 --- a/backend/src/controllers/__tests__/disposalBatch.integration.test.ts +++ b/backend/src/controllers/__tests__/disposalBatch.integration.test.ts @@ -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] diff --git a/backend/src/controllers/__tests__/disposalController.state-machine.test.ts b/backend/src/controllers/__tests__/disposalController.state-machine.test.ts index 4c51f6f..9c6d157 100644 --- a/backend/src/controllers/__tests__/disposalController.state-machine.test.ts +++ b/backend/src/controllers/__tests__/disposalController.state-machine.test.ts @@ -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 | 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 { diff --git a/backend/src/controllers/__tests__/disposalController.visibility.test.ts b/backend/src/controllers/__tests__/disposalController.visibility.test.ts index 46d7e28..f003caf 100644 --- a/backend/src/controllers/__tests__/disposalController.visibility.test.ts +++ b/backend/src/controllers/__tests__/disposalController.visibility.test.ts @@ -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) { diff --git a/backend/src/controllers/__tests__/equipmentController.update-status.test.ts b/backend/src/controllers/__tests__/equipmentController.update-status.test.ts index 3bb1e95..3f29a39 100644 --- a/backend/src/controllers/__tests__/equipmentController.update-status.test.ts +++ b/backend/src/controllers/__tests__/equipmentController.update-status.test.ts @@ -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: { diff --git a/backend/src/controllers/disposalController.ts b/backend/src/controllers/disposalController.ts index 9b15254..7e1d410 100644 --- a/backend/src/controllers/disposalController.ts +++ b/backend/src/controllers/disposalController.ts @@ -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 = | 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) => { 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() + const confirmed = new Map }>() const lockedIds = new Set() 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>, + confirmation?: Map +) => { + 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>, + confirmation: Map +) => { + 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() + 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, diff --git a/backend/src/controllers/equipmentController.ts b/backend/src/controllers/equipmentController.ts index 3c10576..fdeeaea 100644 --- a/backend/src/controllers/equipmentController.ts +++ b/backend/src/controllers/equipmentController.ts @@ -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) } } diff --git a/backend/src/controllers/inventoryController.ts b/backend/src/controllers/inventoryController.ts index 322e498..d6c0eb1 100644 --- a/backend/src/controllers/inventoryController.ts +++ b/backend/src/controllers/inventoryController.ts @@ -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)) } } diff --git a/backend/src/controllers/publicInventoryController.ts b/backend/src/controllers/publicInventoryController.ts index a6af82f..e99e305 100644 --- a/backend/src/controllers/publicInventoryController.ts +++ b/backend/src/controllers/publicInventoryController.ts @@ -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, '提交盘点异常失败') } } diff --git a/backend/src/services/__tests__/inventoryIdentity.test.ts b/backend/src/services/__tests__/inventoryIdentity.test.ts index cb10996..ffbf71f 100644 --- a/backend/src/services/__tests__/inventoryIdentity.test.ts +++ b/backend/src/services/__tests__/inventoryIdentity.test.ts @@ -113,6 +113,7 @@ test('新盘点任务后续请求持续核验当前账号与盘点责任人一 } } const request = { + query: { task_token: 'public-task-token' }, session: { user: { id: 9 }, inventoryParticipant: { diff --git a/backend/src/services/assetMovementService.ts b/backend/src/services/assetMovementService.ts index 13218ef..22e7450 100644 --- a/backend/src/services/assetMovementService.ts +++ b/backend/src/services/assetMovementService.ts @@ -328,8 +328,8 @@ export const borrowAssetTree = async ( ) const equipmentIds = items.map((item) => item.id) - const activeBorrowRows = await client.$queryRaw>(Prisma.sql` - SELECT id, equipment_id + const activeBorrowRows = await client.$queryRaw>(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>(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) { diff --git a/backend/src/services/inventoryService.ts b/backend/src/services/inventoryService.ts index 831f31d..233a0b2 100644 --- a/backend/src/services/inventoryService.ts +++ b/backend/src/services/inventoryService.ts @@ -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, diff --git a/backend/src/utils/disposalSubmission.ts b/backend/src/utils/disposalSubmission.ts index 6e80185..1400b13 100644 --- a/backend/src/utils/disposalSubmission.ts +++ b/backend/src/utils/disposalSubmission.ts @@ -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 } diff --git a/frontend/scripts/test-borrow-person-search.ts b/frontend/scripts/test-borrow-person-search.ts index 87be4bf..2a9f098 100644 --- a/frontend/scripts/test-borrow-person-search.ts +++ b/frontend/scripts/test-borrow-person-search.ts @@ -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, '精确匹配时应支持直接选中') diff --git a/frontend/scripts/test-scan-request-order.mjs b/frontend/scripts/test-scan-request-order.mjs new file mode 100644 index 0000000..7c9ae66 --- /dev/null +++ b/frontend/scripts/test-scan-request-order.mjs @@ -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(/ + + diff --git a/frontend/src/components/DisposalAssetPicker.vue b/frontend/src/components/DisposalAssetPicker.vue new file mode 100644 index 0000000..cc599ba --- /dev/null +++ b/frontend/src/components/DisposalAssetPicker.vue @@ -0,0 +1,130 @@ + + + diff --git a/frontend/src/layouts/MainLayout.vue b/frontend/src/layouts/MainLayout.vue index 55d0616..086c119 100644 --- a/frontend/src/layouts/MainLayout.vue +++ b/frontend/src/layouts/MainLayout.vue @@ -1,17 +1,17 @@ + + diff --git a/frontend/src/style.css b/frontend/src/style.css index 575e780..d738a76 100644 --- a/frontend/src/style.css +++ b/frontend/src/style.css @@ -12,7 +12,7 @@ --text-primary: #ffffff; --text-secondary: #a1a1a1; - --text-tertiary: #6e6e6e; + --text-tertiary: #949494; --border-color: #2a2a2a; --border-hover: #3a3a3a; diff --git a/frontend/src/utils/assetCharts.ts b/frontend/src/utils/assetCharts.ts new file mode 100644 index 0000000..560e6df --- /dev/null +++ b/frontend/src/utils/assetCharts.ts @@ -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 } diff --git a/frontend/src/utils/dialogFocus.ts b/frontend/src/utils/dialogFocus.ts new file mode 100644 index 0000000..f22c3b2 --- /dev/null +++ b/frontend/src/utils/dialogFocus.ts @@ -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('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() + } +} diff --git a/frontend/src/views/Login.vue b/frontend/src/views/Login.vue index 99aaa6d..7bcfa8c 100644 --- a/frontend/src/views/Login.vue +++ b/frontend/src/views/Login.vue @@ -17,8 +17,9 @@
- +
- +
-
+ @@ -50,7 +52,7 @@ {{ loading ? '登录中...' : '进入系统' }} - diff --git a/frontend/src/views/borrow/BorrowList.vue b/frontend/src/views/borrow/BorrowList.vue index c89ca80..610d6ca 100644 --- a/frontend/src/views/borrow/BorrowList.vue +++ b/frontend/src/views/borrow/BorrowList.vue @@ -8,7 +8,7 @@
扫码出库 扫码入库 -
@@ -34,9 +34,9 @@
-
+
- @@ -46,19 +46,26 @@ v-model.trim="filters.person_name" class="input" type="text" + aria-label="使用者" placeholder="输入花名、姓名或工号" - @keyup.enter="handleSearch" /> - +
+ + +
-
+ + +
@@ -109,7 +116,7 @@
-

+

当前筛选条件下暂无记录。

@@ -161,7 +168,7 @@ - + 当前筛选条件下暂无记录。 @@ -225,6 +232,8 @@ type BorrowFilters = Pick[0], 'status' | const borrowRecords = ref([]) 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 } diff --git a/frontend/src/views/borrow/BorrowScan.vue b/frontend/src/views/borrow/BorrowScan.vue index 3cc898f..bd9b1b6 100644 --- a/frontend/src/views/borrow/BorrowScan.vue +++ b/frontend/src/views/borrow/BorrowScan.vue @@ -16,10 +16,10 @@

扫码出库

- -
@@ -32,7 +32,7 @@

识别结果

-

{{ equipmentInfo ? '已识别资产' : '等待扫码' }}

+

{{ lookupLoading ? '读取中' : equipmentInfo ? '已识别资产' : '等待扫码' }}

当前可借

@@ -40,7 +40,7 @@
-
+

手动输入

@@ -109,7 +109,10 @@ 没有匹配到可借资产。若你已经知道准确编码,也可以直接点“按编码读取”。

- + + +

正在读取资产…

+
@@ -120,7 +123,7 @@ {{ equipmentInfo.status }} - @@ -190,7 +193,7 @@

使用者信息

-
+
@@ -275,6 +278,7 @@ placeholder="请输入备注信息" >
+
-
+
@@ -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(null) const persons = ref([]) 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() + } } ) diff --git a/frontend/src/views/borrow/ReturnScan.vue b/frontend/src/views/borrow/ReturnScan.vue index 8454e32..e0fd9b4 100644 --- a/frontend/src/views/borrow/ReturnScan.vue +++ b/frontend/src/views/borrow/ReturnScan.vue @@ -14,10 +14,10 @@

扫码归还

- -
@@ -26,7 +26,7 @@

当前进度

-

{{ borrowRecordInfo ? '待确认归还' : '等待扫码' }}

+

{{ lookupLoading ? '读取中' : borrowRecordInfo ? '待确认归还' : '等待扫码' }}

借用记录

@@ -45,6 +45,7 @@
+

正在读取资产和借用记录…

+ +

手动输入

@@ -68,7 +71,6 @@ class="input" placeholder="输入资产编码 / 名称 / 型号 / 地址搜索" @keyup.enter="handleManualAssetSubmit" - @focus="handleFocus" />
-
+
@@ -137,7 +139,7 @@

资产信息

已借出
-
@@ -180,12 +182,13 @@ type="text" class="input" placeholder="输入花名 / 姓名 / 工号 / 部门搜索" + :disabled="loading" @keyup.enter="handleRecordKeywordSubmit" />

- {{ borrowRecordInfo.borrow_records.length > 1 - ? '这台资产存在多条未归还记录,请搜索并点选正确使用者。' - : '这台资产当前只有 1 条未归还记录,系统已自动帮你选中。' }} + {{ borrowRecordInfo.borrow_records.length === 1 && selectedBorrowRecordId + ? '这台资产当前只有 1 条未归还记录,已选中。' + : '请搜索并点选正确的归还使用者。' }}

@@ -201,6 +204,7 @@ type="button" class="touch-option" :class="{ 'is-active': selectedBorrowRecordId === record.id }" + :disabled="loading" @click="selectBorrowRecord(record)" >
@@ -308,7 +312,7 @@

归还信息

-
+
- +
+
@@ -763,7 +772,7 @@ @@ -778,12 +787,11 @@ diff --git a/frontend/src/views/settings/components/PersonManagement.vue b/frontend/src/views/settings/components/PersonManagement.vue index a72513d..208f9ff 100644 --- a/frontend/src/views/settings/components/PersonManagement.vue +++ b/frontend/src/views/settings/components/PersonManagement.vue @@ -351,7 +351,6 @@