diff --git a/backend/src/services/__tests__/hrBorrowDepartment.integration.test.ts b/backend/src/services/__tests__/hrBorrowDepartment.integration.test.ts index a8e42df..5faf854 100644 --- a/backend/src/services/__tests__/hrBorrowDepartment.integration.test.ts +++ b/backend/src/services/__tests__/hrBorrowDepartment.integration.test.ts @@ -66,6 +66,7 @@ test('花名册借用资产归属同步在隔离 MySQL 验证', { const moved = await person() const departed = await person() const itPerson = await person() + const unaffectedPerson = await person(otherDepartment.id) const it = await prisma.user.create({ data: { username: `${prefix}-it`, name: '测试IT', password: 'local-only', role: 'it', status: 'inactive', person_id: itPerson.id } }) userIds.push(it.id) const admin = await prisma.user.create({ data: { username: `${prefix}-admin`, name: '测试管理员', password: 'local-only', role: 'admin', status: 'inactive' } }) @@ -77,12 +78,29 @@ test('花名册借用资产归属同步在隔离 MySQL 验证', { const returnedLoan = await loan(returned, departed) const blockedDeparture = await equipment() await equipment({ parent_id: blockedDeparture.id, mount_status: 'mounted' }) - const blockedLoan = await loan(blockedDeparture, departed) + const blockedLoan = await loan(blockedDeparture, departed, '[]') const shared = await equipment({ total_quantity: 2, total_value: 200, borrowed_value: 200 }) const sharedLoan = await loan(shared, moved) const colleagueLoan = await loan(shared, itPerson) const historical = await equipment({ department_id: otherDepartment.id }) await loan(historical, itPerson) + const inactiveDepartment = await department('已停用部门') + await prisma.department.update({ where: { id: inactiveDepartment.id }, data: { status: 'inactive' } }) + const inactiveRoot = await equipment({ department_id: inactiveDepartment.id }) + const inactiveLoan = await loan(inactiveRoot, itPerson) + const matchedRoot = await equipment() + const inactiveChild = await equipment({ + department_id: inactiveDepartment.id, parent_id: matchedRoot.id, mount_status: 'mounted' + }) + const matchedLoan = await loan(matchedRoot, itPerson) + const publicPerson = await person() + await prisma.person.update({ where: { id: publicPerson.id }, data: { source_system: 'system_reserved' } }) + const publicRoot = await equipment({ department_id: inactiveDepartment.id }) + await loan(publicRoot, publicPerson) + const missingLoan = await equipment({ department_id: inactiveDepartment.id }) + const returnedEarlier = await equipment({ department_id: inactiveDepartment.id, status: '可用', remaining_quantity: 1 }) + const closed = await loan(returnedEarlier, itPerson) + await prisma.borrowRecord.update({ where: { id: closed.id }, data: { status: '已归还', return_time: new Date() } }) const oldOther = await prisma.department.findFirst({ where: { name: '其他', source_system: 'ding_hr_business' } }) const env: Record = { @@ -101,7 +119,8 @@ test('花名册借用资产归属同步在隔离 MySQL 验证', { input() { return this }, query: async (statement: string) => ({ recordset: statement.includes('hr_employee_dimission') ? [{ id: 17, sourceUserId: departed.source_userid, lastWorkDay: Date.now() - 3600000, status: 2 }] - : [roster(moved, newDepartment.name), roster(itPerson, oldDepartment.name), roster(departed, oldDepartment.name, '5')] }) + : [roster(moved, newDepartment.name), roster(itPerson, oldDepartment.name), + roster(unaffectedPerson, otherDepartment.name), roster(departed, oldDepartment.name, '5')] }) }), close: async () => {} }) try { const result = await runHrSync(prefix, 'manual') @@ -109,7 +128,7 @@ test('花名册借用资产归属同步在隔离 MySQL 验证', { if (newOther) departmentIds.push(newOther.id) assert.equal(result.auto_return?.returned, 1) assert.equal(result.auto_return?.pending, 1) - assert.deepEqual(result.auto_department, { reassigned: 2, review: 1, retry: 0 }) + assert.deepEqual(result.auto_department, { reassigned: 4, review: 1, retry: 0 }) for (const before of [root, child]) { const after = await prisma.equipment.findUniqueOrThrow({ where: { id: before.id } }) assert.equal(after.department_id, newDepartment.id) @@ -120,6 +139,16 @@ test('花名册借用资产归属同步在隔离 MySQL 验证', { assert.deepEqual(await prisma.borrowRecord.findUniqueOrThrow({ where: { id: colleagueLoan.id } }), colleagueLoan) assert.equal((await prisma.equipment.findUniqueOrThrow({ where: { id: shared.id } })).department_id, oldDepartment.id) assert.equal((await prisma.equipment.findUniqueOrThrow({ where: { id: historical.id } })).department_id, otherDepartment.id) + for (const before of [inactiveRoot, inactiveChild]) { + const after = await prisma.equipment.findUniqueOrThrow({ where: { id: before.id } }) + assert.equal(after.department_id, oldDepartment.id) + assert.deepEqual({ ...after, department_id: before.department_id, updated_at: before.updated_at }, before) + } + for (const before of [publicRoot, missingLoan, returnedEarlier]) { + assert.deepEqual(await prisma.equipment.findUniqueOrThrow({ where: { id: before.id } }), before) + } + assert.deepEqual(await prisma.borrowRecord.findUniqueOrThrow({ where: { id: inactiveLoan.id } }), inactiveLoan) + assert.deepEqual(await prisma.borrowRecord.findUniqueOrThrow({ where: { id: matchedLoan.id } }), matchedLoan) assert.equal((await prisma.borrowRecord.findUniqueOrThrow({ where: { id: returnedLoan.id } })).status, '已归还') const returnAsset = await prisma.equipment.findUniqueOrThrow({ where: { id: returned.id } }) assert.equal(returnAsset.department_id, null); assert.equal(returnAsset.storage_location_id, storage.id) @@ -132,7 +161,7 @@ test('花名册借用资产归属同步在隔离 MySQL 验证', { assert.deepEqual(await prisma.borrowRecord.findUniqueOrThrow({ where: { id: blockedLoan.id } }), blockedLoan) const pendingCount = () => prisma.operationLog.count({ where: { equipment_id: { in: equipmentIds }, operation_type: '人事资产结果待通知' } }) - assert.equal(await pendingCount(), 4) + assert.equal(await pendingCount(), 6) assert.equal(await prisma.notification.count({ where: { related_sync_job_id: result.sync_job_id } }), 0) await prisma.user.updateMany({ where: { id: { in: userIds } }, data: { status: 'active' } }) const originalTransaction = prisma.$transaction @@ -154,7 +183,7 @@ test('花名册借用资产归属同步在隔离 MySQL 验证', { try { await assert.rejects(runHrSync(prefix, 'manual'), /fixture interrupted notification transaction/) } finally { prisma.$transaction = originalTransaction } assert.equal(consumeAttempted, true) - assert.equal(await pendingCount(), 4) + assert.equal(await pendingCount(), 6) assert.equal(await prisma.dingTalkDelivery.count({ where: { recipient_user_id: it.id, event_type: 'hr_sync_attention' } }), 0) assert.equal(await prisma.userNotification.count({ where: { user_id: it.id } }), 0) @@ -163,9 +192,9 @@ test('花名册借用资产归属同步在隔离 MySQL 验证', { assert.equal(retried.auto_department, undefined) assert.equal(await pendingCount(), 0) const job = await prisma.syncJob.findUniqueOrThrow({ where: { id: retried.sync_job_id }, include: { changes: true } }) - assert.equal(job.changes.length, 4) + assert.equal(job.changes.length, 6) const consumed = await prisma.operationLog.findMany({ where: { equipment_id: { in: equipmentIds }, operation_type: '人事资产结果已通知' } }) - assert.equal(consumed.length, 4) + assert.equal(consumed.length, 6) assert.ok(consumed.every(row => JSON.parse(row.operation_details!).sync_job_id === job.id)) for (const change of job.changes.filter(change => change.change_type.startsWith('person_assets_'))) { assert.equal(change.processing_status, change.change_type === 'person_assets_review' ? 'pending' : 'processed') @@ -178,13 +207,17 @@ test('花名册借用资产归属同步在隔离 MySQL 验证', { assert.equal(deliveries[0].status, 'pending') const ding = (JSON.parse(deliveries[0].payload_json).content as string).replace(/\\-/g, '-') for (const content of [notice.content!, ding]) { - for (const asset of [root, child, shared, returned, blockedDeparture]) assert.ok(content.includes(asset.equipment_code)) + for (const asset of [root, child, shared, returned, blockedDeparture, inactiveRoot, inactiveChild]) { + assert.ok(content.includes(asset.equipment_code)) + } assert.match(content, /无需扫码/); assert.match(content, /待核对/) assert.doesNotMatch(content, /快捷入库|请逐项核对/) } const repeated = await runHrSync(prefix, 'manual') assert.equal(repeated.changes_count, 0) assert.equal(await flowCount(root.id), 1) + assert.equal(await flowCount(inactiveRoot.id), 1) + assert.equal(await flowCount(matchedRoot.id), 1) assert.equal(await flowCount(returned.id), 1) assert.equal(await flowCount(blockedDeparture.id), 0) assert.equal(await prisma.dingTalkDelivery.count({ where: { recipient_user_id: it.id, event_type: 'hr_sync_attention' } }), 1) diff --git a/backend/src/services/__tests__/hrDepartureReturn.integration.test.ts b/backend/src/services/__tests__/hrDepartureReturn.integration.test.ts index 5c01159..5b210eb 100644 --- a/backend/src/services/__tests__/hrDepartureReturn.integration.test.ts +++ b/backend/src/services/__tests__/hrDepartureReturn.integration.test.ts @@ -28,6 +28,7 @@ test('正式离职自动入库在隔离 MySQL 验证库存、审计、冲突和 try { const department = await prisma.department.create({ data: { name: prefix } }); departmentIds.push(department.id) const storage = await prisma.storageLocation.create({ data: { name: prefix } }); storageIds.push(storage.id) + const accessoryStorage = await prisma.storageLocation.create({ data: { name: `${prefix}-配件` } }); storageIds.push(accessoryStorage.id) const user = await prisma.user.create({ data: { username: prefix, name: prefix, password: 'isolated-db-fixture' } }); userIds.push(user.id) const person = async (status = 'inactive') => { const row = await prisma.person.create({ data: { @@ -56,6 +57,13 @@ test('正式离职自动入库在隔离 MySQL 验证库存、审计、冲突和 id: `${prefix}-event`, sourceUserId: borrower.source_userid, lastWorkDay: lastWorkDay.getTime(), status }) const process = (borrowers: Person[]) => returnAssetsForHrDepartures(selectConfirmedHrDepartures(borrowers.map(row => event(row)), new Set(), from, now)) + const mountHistory = (child: Equipment, parent: Equipment, timestamp: string, operation = 'mount') => prisma.mountHistory.create({ data: { + child_id: child.id, parent_id: parent.id, operation_type: operation, operated_by: user.id, operated_at: new Date(timestamp) + } }) + const returnEvidence = async (root: Equipment) => { + const log = await prisma.operationLog.findFirstOrThrow({ where: { equipment_id: root.id, operation_type: '离职资产自动入库' } }) + return JSON.parse(log.operation_details!).return_evidence + } await t.test('复用正常归还并保留库位,清空主机配件归属,只写一条系统流水与审计', async () => { const borrower = await person() @@ -82,6 +90,67 @@ test('正式离职自动入库在隔离 MySQL 验证库存、审计、冲突和 const detail = JSON.parse(logs[0].operation_details!) assert.equal(detail.borrow_record_id, record.id); assert.equal(detail.source_event_id, `${prefix}-event`) assert.equal(detail.movement_id, movements[0].id) + assert.equal(detail.return_evidence.method, 'borrow_snapshot_match') + }) + + await t.test('缺失旧快照按锁定现树入库,每件保留各自原库位和挂载关系', async () => { + const borrower = await person() + const root = await equipment() + const child = await equipment({ parent_id: root.id, mount_status: 'mounted', storage_location_id: accessoryStorage.id }) + const nested = await equipment({ parent_id: child.id, mount_status: 'mounted', storage_location_id: null }) + const record = await loan(root, borrower) + assert.deepEqual((await process([borrower])).outcomes[0].assets.map(item => item.equipmentId), [root.id, child.id, nested.id]) + const saved = await prisma.borrowRecord.findUniqueOrThrow({ where: { id: record.id } }) + assert.equal(saved.status, '已归还'); assert.equal(saved.children_snapshot, null) + const expected = [root, child, nested].map(item => ({ equipment_id: item.id, parent_id: item.parent_id, storage_location_id: item.storage_location_id })) + assert.deepEqual(await returnEvidence(root), { method: 'locked_tree_without_snapshot', asset_tree: expected }) + for (const before of [root, child, nested]) { + const after = await prisma.equipment.findUniqueOrThrow({ where: { id: before.id } }) + assert.equal(after.storage_location_id, before.storage_location_id) + assert.equal(after.parent_id, before.parent_id); assert.equal(after.mount_status, before.mount_status) + assert.equal(after.status, '可用'); assert.equal(after.department_id, null) + } + }) + + await t.test('真实借出后新增挂载流水解释整树时归还,保留原快照并记录命中流水', async () => { + const borrower = await person() + const root = await equipment() + const original = await equipment({ parent_id: root.id, mount_status: 'mounted' }) + const added = await equipment({ parent_id: root.id, mount_status: 'mounted', storage_location_id: accessoryStorage.id }) + const addedNested = await equipment({ parent_id: added.id, mount_status: 'mounted' }) + const snapshot = JSON.stringify([{ id: original.id, parent_id: root.id }]) + const record = await loan(root, borrower, snapshot) + await mountHistory(added, original, '2026-11-09T04:30:00Z') + const first = await mountHistory(added, root, '2026-11-09T05:00:00Z') + const second = await mountHistory(addedNested, added, '2026-11-09T06:00:00Z') + const result = await process([borrower]) + assert.deepEqual([result.returned, result.pending, result.failed], [1, 0, 0]) + const stored = await prisma.borrowRecord.findUniqueOrThrow({ where: { id: record.id } }) + assert.equal(stored.children_snapshot, snapshot); assert.equal(stored.status, '已归还') + const evidence = await returnEvidence(root) + assert.equal(evidence.method, 'post_borrow_mounts') + assert.deepEqual(evidence.mount_histories.map((row: { id: number }) => row.id), [first.id, second.id]) + assert.equal((await prisma.equipment.findUniqueOrThrow({ where: { id: added.id } })).storage_location_id, accessoryStorage.id) + }) + + await t.test('借出前、父级不符、后续已卸下、部分流水及换件均不足以证明增挂', async () => { + for (const scenario of ['before-borrow', 'wrong-parent', 'superseded', 'partial', 'replacement']) { + const borrower = await person() + const root = await equipment() + const added = await equipment({ parent_id: root.id, mount_status: 'mounted' }) + const replaced = scenario === 'replacement' ? await equipment({ parent_id: null, mount_status: 'unmounted' }) : null + const snapshot = replaced ? JSON.stringify([{ id: replaced.id, parent_id: root.id }]) : '[]' + const record = await loan(root, borrower, snapshot) + const expectedParent = scenario === 'wrong-parent' ? await equipment() : root + await mountHistory(added, expectedParent, scenario === 'before-borrow' ? '2026-11-09T03:59:00Z' : '2026-11-09T05:00:00Z') + if (scenario === 'superseded') await mountHistory(added, root, '2026-11-09T06:00:00Z', 'unmount') + if (scenario === 'partial') await equipment({ parent_id: added.id, mount_status: 'mounted' }) + const result = await process([borrower]) + assert.deepEqual([result.returned, result.pending, result.failed], [0, 1, 0], scenario) + const saved = await prisma.borrowRecord.findUniqueOrThrow({ where: { id: record.id } }) + assert.equal(saved.status, '已借出'); assert.equal(saved.children_snapshot, snapshot) + assert.equal(await prisma.assetTransferRecord.count({ where: { root_equipment_id: root.id } }), 0) + } }) await t.test('历史离职、未来离职、仍在名单、无确证停用以及事后补录均无写入', async () => { @@ -103,14 +172,15 @@ test('正式离职自动入库在隔离 MySQL 验证库存、审计、冲突和 }) await t.test('配件快照差异、库存异常、维修/报废、挂载树多持有人和独立配件借用留待人工', async () => { - for (const scenario of ['changed-accessory', 'bad-stock', 'other-owner', 'child-borrow', 'maintenance', 'disposal']) { + for (const scenario of ['changed-accessory', 'bad-stock', 'bad-mount-state', 'other-owner', 'child-borrow', 'maintenance', 'disposal']) { const borrower = await person() const root = await equipment(['other-owner', 'child-borrow', 'bad-stock'].includes(scenario) ? { total_quantity: 2 } : {}) const child = scenario === 'other-owner' || scenario === 'child-borrow' ? await equipment({ parent_id: root.id, mount_status: 'mounted' }) : undefined - const snapshot = child ? JSON.stringify([{ id: child.id, parent_id: root.id }]) : undefined + const snapshot = child ? JSON.stringify([{ id: child.id, parent_id: root.id }]) : scenario === 'changed-accessory' ? '[]' : undefined const record = await loan(root, borrower, snapshot) if (scenario === 'changed-accessory') await equipment({ parent_id: root.id, mount_status: 'mounted' }) + if (scenario === 'bad-mount-state') await equipment({ parent_id: root.id, mount_status: 'unmounted' }) if (scenario === 'other-owner') await loan(root, await person('active'), snapshot) if (scenario === 'child-borrow') await loan(child!, await person('active')) if (scenario === 'maintenance') await prisma.maintenanceRecord.create({ data: { @@ -174,6 +244,7 @@ test('正式离职自动入库在隔离 MySQL 验证库存、审计、冲突和 await prisma.$transaction(async (tx) => { await tx.operationLog.deleteMany({ where: { equipment_id: { in: equipmentIds }, username: 'system-hr-sync' } }) await tx.assetTransferRecord.deleteMany({ where: { root_equipment_id: { in: equipmentIds } } }) + await tx.mountHistory.deleteMany({ where: { child_id: { in: equipmentIds } } }) await tx.maintenanceRecord.deleteMany({ where: { equipment_id: { in: equipmentIds } } }) await tx.disposalRecord.deleteMany({ where: { equipment_id: { in: equipmentIds } } }) await tx.borrowRecord.deleteMany({ where: { equipment_id: { in: equipmentIds } } }) diff --git a/backend/src/services/hrBorrowDepartmentService.ts b/backend/src/services/hrBorrowDepartmentService.ts index fcc470a..c8c0e24 100644 --- a/backend/src/services/hrBorrowDepartmentService.ts +++ b/backend/src/services/hrBorrowDepartmentService.ts @@ -1,6 +1,6 @@ import { Prisma } from '@prisma/client' import prisma from '../utils/prisma' -import { HR_BUSINESS_DEPARTMENT_SOURCE_SYSTEM, HR_SOURCE_SYSTEM } from '../utils/organization' +import { HR_BUSINESS_DEPARTMENT_SOURCE_SYSTEM, HR_SOURCE_SYSTEM, OTHER_DEPARTMENT_NAME } from '../utils/organization' import { createAssetMovementRecord, loadAndLockAssetTree } from './assetMovementService' import { queueHrAssetOutcome } from './hrAssetOutcomeStore' import type { HrAssetSyncOutcome, OpenBorrowAssetPreview } from './hrSyncHelpers' @@ -60,21 +60,33 @@ const buildOutcome = (task: DepartmentTask, kind: HrAssetSyncOutcome['kind'], as kind, assets, departmentName: task.departmentName, reason }) -const applyDepartmentTask = (logId: number, task: DepartmentTask) => prisma.$transaction(async tx => { +const applyDepartmentTask = ( + logId: number | null, + task: DepartmentTask, + activeSourceUserIds?: ReadonlySet +) => prisma.$transaction(async tx => { const tree = await loadAndLockAssetTree(tx, task.root.equipmentId) const root = tree[0] - const [log] = await tx.$queryRaw>( - Prisma.sql`SELECT operation_type FROM operation_log WHERE id = ${logId} FOR UPDATE` - ) - if (log?.operation_type !== PENDING) return null - const finish = (operationType: string, details: Record = {}) => tx.operationLog.update({ - where: { id: logId }, - data: { operation_type: operationType, operation_details: JSON.stringify({ ...task, ...details }) } - }) + if (logId !== null) { + const [log] = await tx.$queryRaw>( + Prisma.sql`SELECT operation_type FROM operation_log WHERE id = ${logId} FOR UPDATE` + ) + if (log?.operation_type !== PENDING) return null + } + const finish = async (operationType: string, details: Record = {}) => { + const data = { operation_type: operationType, operation_details: JSON.stringify({ ...task, ...details }) } + if (logId !== null) { + await tx.operationLog.update({ where: { id: logId }, data }) + } else if (operationType === TRANSFERRED) { + await tx.operationLog.create({ data: { + ...data, username: SYSTEM, equipment_id: root.id, equipment_code: root.equipment_code + } }) + } + } const review = async (reason: string) => { await finish(REVIEW, { reason }) const outcome = buildOutcome(task, 'review', [task.root], reason) - await queueHrAssetOutcome(tx, outcome) + await queueHrAssetOutcome(tx, outcome, JSON.stringify(['department', task.borrowRecordIds, task.toDepartmentId, reason])) return outcome } const equipmentIds = tree.map(item => item.id) @@ -101,27 +113,39 @@ const applyDepartmentTask = (logId: number, task: DepartmentTask) => prisma.$tra if (people.length !== personIds.length || people.some(row => row.status !== 'active' || row.main_department_id !== task.toDepartmentId)) { return review('同一资产仍有其他持有人,主部门不一致') } + const allInRoster = activeSourceUserIds && people.every(row => row.source_system === HR_SOURCE_SYSTEM + && row.source_userid && activeSourceUserIds.has(row.source_userid)) + if (logId === null && !allInRoster) return null if (root.parent_id !== null || root.total_quantity <= 0 || root.remaining_quantity < 0 + || root.mount_status === 'mounted' || root.status !== (root.remaining_quantity > 0 ? '可用' : '已借出') || root.total_quantity - root.remaining_quantity !== loans.length || loans.some(loan => loan.equipment_id !== root.id || loan.return_time !== null) - || tree.slice(1).some(item => item.status !== '已借出' || item.total_quantity <= 0 || item.remaining_quantity !== 0)) { + || tree.slice(1).some(item => item.mount_status !== 'mounted' || item.status !== '已借出' + || item.total_quantity <= 0 || item.remaining_quantity !== 0)) { return review('资产库存、挂载或借用状态需要核对') } - if (tree.some(item => item.department_id !== task.fromDepartmentId && item.department_id !== task.toDepartmentId)) { - return review('资产当前归属与人员变动前的部门不一致') - } const changed = tree.filter(item => item.department_id !== task.toDepartmentId) if (!changed.length) { await finish(UNCHANGED, { reason: '资产已归属新主部门' }) return null } - const [department] = await tx.$queryRaw>(Prisma.sql` - SELECT status, source_system, name FROM department WHERE id = ${task.toDepartmentId} FOR UPDATE + const previousIds = [...new Set(changed.flatMap(item => item.department_id === null ? [] : [item.department_id]))] + const departmentIds = allInRoster ? [...previousIds, task.toDepartmentId] : [task.toDepartmentId] + const departments = await tx.$queryRaw>(Prisma.sql` + SELECT id, status, source_system, name FROM department WHERE id IN (${Prisma.join(departmentIds)}) ORDER BY id FOR UPDATE `) + const department = departments.find(row => row.id === task.toDepartmentId) if (!department || department.status !== 'active' || department.source_system !== HR_BUSINESS_DEPARTMENT_SOURCE_SYSTEM) { return review('新主部门已停用或无法核实') } + const fromInactiveDepartment = allInRoster && department.name !== OTHER_DEPARTMENT_NAME + && departments.some(row => previousIds.includes(row.id) && row.status === 'inactive' + && row.source_system === HR_BUSINESS_DEPARTMENT_SOURCE_SYSTEM) + if (logId === null && !fromInactiveDepartment) return null + if (!fromInactiveDepartment && changed.some(item => item.department_id !== task.fromDepartmentId)) { + return review('资产当前归属与人员变动前的部门不一致') + } const [maintenance, disposal] = await Promise.all([ tx.maintenanceRecord.findFirst({ where: { equipment_id: { in: equipmentIds }, status: 'in_progress' }, select: { id: true } }), tx.disposalRecord.findFirst({ where: { @@ -131,9 +155,10 @@ const applyDepartmentTask = (logId: number, task: DepartmentTask) => prisma.$tra ]) if (maintenance || disposal) return review('资产树存在未完成的维修或报废') + const reason = fromInactiveDepartment ? '原部门停用,按在借使用者现主部门调整归属' : '花名册主部门变动,借用资产自动调整归属' const movement = await createAssetMovementRecord(tx, { items: tree, actionType: 'transfer', toDepartmentId: task.toDepartmentId, - toDepartmentName: department.name, operatedBy: null, reason: '花名册主部门变动,借用资产自动调整归属' + toDepartmentName: department.name, operatedBy: null, reason }) for (const item of changed) { const updated = await tx.equipment.updateMany({ @@ -143,27 +168,63 @@ const applyDepartmentTask = (logId: number, task: DepartmentTask) => prisma.$tra if (updated.count !== 1) throw new Error('资产归属已变化,稍后重新核对') } const assets = changed.map(item => ({ equipmentId: item.id, equipmentCode: item.equipment_code, equipmentName: item.equipment_name })) - await finish(TRANSFERRED, { movementId: movement.id, assets }) + await finish(TRANSFERRED, { movementId: movement.id, reason, assets }) const outcome = buildOutcome({ ...task, departmentName: department.name }, 'reassigned', assets) await queueHrAssetOutcome(tx, outcome) return outcome }, { isolationLevel: Prisma.TransactionIsolationLevel.ReadCommitted }) -export const applyHrBorrowDepartmentChanges = async (): Promise => { +const findInactiveDepartmentLoans = () => prisma.$queryRaw>(Prisma.sql` + WITH RECURSIVE affected AS ( + SELECT e.id, e.parent_id FROM equipment e JOIN department d ON d.id = e.department_id + WHERE e.status IN ('可用', '已借出') AND d.status = 'inactive' + AND d.source_system = ${HR_BUSINESS_DEPARTMENT_SOURCE_SYSTEM} + UNION DISTINCT + SELECT e.id, e.parent_id FROM equipment e JOIN affected a ON e.id = a.parent_id + ) + SELECT e.id AS equipmentId, e.equipment_code AS equipmentCode, e.equipment_name AS equipmentName, + b.id AS loanId, p.id AS personId, p.source_userid AS sourceUserId, p.nickname AS personName, + e.department_id AS fromDepartmentId, d.id AS toDepartmentId, d.name AS departmentName + FROM affected a JOIN equipment e ON e.id = a.id + JOIN borrow_record b ON b.equipment_id = e.id AND b.status = '已借出' AND b.return_time IS NULL + JOIN person p ON p.id = b.person_id AND p.status = 'active' AND p.source_system = ${HR_SOURCE_SYSTEM} + JOIN department d ON d.id = p.main_department_id AND d.status = 'active' + AND d.source_system = ${HR_BUSINESS_DEPARTMENT_SOURCE_SYSTEM} AND d.name <> ${OTHER_DEPARTMENT_NAME} + WHERE a.parent_id IS NULL AND p.source_userid IS NOT NULL + ORDER BY e.id, b.id +`) + +export const applyHrBorrowDepartmentChanges = async ( + activeSourceUserIds?: ReadonlySet +): Promise => { const logs = await prisma.operationLog.findMany({ where: { username: SYSTEM, operation_type: PENDING }, orderBy: { id: 'asc' }, select: { id: true, operation_details: true } }) const outcomes: HrAssetSyncOutcome[] = [] - for (const log of logs) { - const task = JSON.parse(log.operation_details!) as DepartmentTask + const attempted = new Set() + const apply = async (task: DepartmentTask, logId: number | null) => { + attempted.add(task.root.equipmentId) try { - const outcome = await applyDepartmentTask(log.id, task) + const outcome = await applyDepartmentTask(logId, task, activeSourceUserIds) if (outcome) outcomes.push(outcome) } catch (error) { - console.error('[hr-sync] borrowed asset department change failed for log', log.id, error) + console.error('[hr-sync] borrowed asset department change failed for asset', task.root.equipmentId, error) outcomes.push(buildOutcome(task, 'retry', [task.root], '本次未完成,下一次同步将重试')) } } + for (const log of logs) { + await apply(JSON.parse(log.operation_details!) as DepartmentTask, log.id) + } + if (!activeSourceUserIds?.size) return outcomes + for (const row of await findInactiveDepartmentLoans()) { + const { equipmentId, equipmentCode, equipmentName, loanId, ...person } = row + if (attempted.has(equipmentId) || !activeSourceUserIds.has(person.sourceUserId)) continue + await apply({ ...person, root: { equipmentId, equipmentCode, equipmentName }, borrowRecordIds: [loanId] }, null) + } return outcomes } diff --git a/backend/src/services/hrDepartureReturnService.ts b/backend/src/services/hrDepartureReturnService.ts index 7718c2a..8fe2f62 100644 --- a/backend/src/services/hrDepartureReturnService.ts +++ b/backend/src/services/hrDepartureReturnService.ts @@ -4,7 +4,7 @@ import { parseBusinessDate } from '../utils/businessDate' import { getShanghaiDayRange } from '../utils/dashboardStatistics' import { HR_SOURCE_SYSTEM } from '../utils/organization' import { getReturnChildrenDiff } from '../utils/returnSnapshot' -import { AssetTreeConflictError, loadAndLockAssetTree } from './assetMovementService' +import { AssetTreeConflictError, loadAndLockAssetTree, type AssetTreeItem } from './assetMovementService' import { completeLockedBorrowReturn } from './borrowReturnService' import { queueHrAssetOutcome } from './hrAssetOutcomeStore' import type { HrAssetSyncOutcome } from './hrSyncHelpers' @@ -62,6 +62,34 @@ export const selectConfirmedHrDepartures = ( type BorrowCandidate = { id: number; equipment_id: number; person_id: number } +const getDepartureReturnEvidence = async ( + tx: Prisma.TransactionClient, + items: AssetTreeItem[], + record: BorrowCandidate & { borrow_time: Date; children_snapshot: string | null } +) => { + if (!record.children_snapshot?.trim()) return { method: 'locked_tree_without_snapshot' } + const diff = getReturnChildrenDiff(items, record) + if (!diff) return { method: 'borrow_snapshot_match' } + if (diff.removed.length > 0) return null + + // Each new edge must have a real mount after checkout. A later detach, + // replacement, or mount to a different parent is not evidence for this edge. + const histories = await tx.mountHistory.findMany({ + where: { child_id: { in: diff.added.map(item => item.id) }, operated_at: { gt: record.borrow_time } }, + select: { id: true, child_id: true, parent_id: true, operation_type: true, operated_at: true }, + orderBy: [{ operated_at: 'desc' }, { id: 'desc' }] + }) + const latestByChild = new Map() + for (const history of histories) if (!latestByChild.has(history.child_id)) latestByChild.set(history.child_id, history) + const verified = [] + for (const item of diff.added) { + const history = latestByChild.get(item.id) + if (history?.operation_type !== 'mount' || history.parent_id !== item.parent_id) return null + verified.push(history) + } + return { method: 'post_borrow_mounts', mount_histories: verified } +} + const returnConfirmedDepartureBorrow = async (candidate: BorrowCandidate, departure: HrDeparture, personName: string) => ( prisma.$transaction(async (tx) => { const items = await loadAndLockAssetTree(tx, candidate.equipment_id) @@ -94,21 +122,24 @@ const returnConfirmedDepartureBorrow = async (candidate: BorrowCandidate, depart return outcome } - if (root.parent_id !== null || root.total_quantity <= 0 || root.remaining_quantity < 0 + if (root.parent_id !== null || root.mount_status === 'mounted' || root.total_quantity <= 0 || root.remaining_quantity < 0 || root.remaining_quantity >= root.total_quantity || root.status !== (root.remaining_quantity > 0 ? '可用' : '已借出') || activeBorrows.length !== root.total_quantity - root.remaining_quantity || activeBorrows.some(row => row.equipment_id !== root.id || row.return_time !== null || (items.length > 1 && row.person_id !== record.person_id)) - || items.slice(1).some(item => item.status !== '已借出' || item.total_quantity <= 0 || item.remaining_quantity !== 0)) { + || items.slice(1).some(item => item.mount_status !== 'mounted' || item.status !== '已借出' + || item.total_quantity <= 0 || item.remaining_quantity !== 0)) { return review('资产树库存、借用状态或持有人需要人工核查') } + let evidence: Awaited> try { - if (getReturnChildrenDiff(items, record)) return review('当前挂载配件与借出时不一致,需要人工确认') + evidence = await getDepartureReturnEvidence(tx, items, record) } catch (error) { if (error instanceof Error && (error as { status?: number }).status === 409) return review(error.message) throw error } + if (!evidence) return review('当前挂载配件与借出时不一致,缺少完整的增挂流水,需要人工确认') const [maintenance, disposal] = await Promise.all([ tx.maintenanceRecord.findFirst({ where: { equipment_id: { in: equipmentIds }, status: 'in_progress' }, select: { id: true } }), tx.disposalRecord.findFirst({ where: { @@ -128,7 +159,11 @@ const returnConfirmedDepartureBorrow = async (candidate: BorrowCandidate, depart operation_details: JSON.stringify({ reason, source_event_id: departure.sourceEventId, source_userid: departure.sourceUserId, last_work_day: departure.lastWorkDay.toISOString(), person_id: record.person_id, - borrow_record_id: record.id, movement_id: movementId, equipment_ids: equipmentIds + borrow_record_id: record.id, movement_id: movementId, equipment_ids: equipmentIds, + return_evidence: { + ...evidence, + asset_tree: items.map(item => ({ equipment_id: item.id, parent_id: item.parent_id, storage_location_id: item.storage_location_id })) + } }) } }) const outcome: HrAssetSyncOutcome = { diff --git a/backend/src/services/hrSyncService.ts b/backend/src/services/hrSyncService.ts index 85b243a..39ef6a7 100644 --- a/backend/src/services/hrSyncService.ts +++ b/backend/src/services/hrSyncService.ts @@ -1967,7 +1967,7 @@ export const runHrSync = async ( autoReturn = failedAutoReturn('无法读取离职人员未归还的借用,未执行自动入库') } } - const departmentOutcomes = await applyHrBorrowDepartmentChanges() + const departmentOutcomes = await applyHrBorrowDepartmentChanges(new Set(persons.map(person => person.sourceUserId))) const departureOutcomes = autoReturn?.outcomes || [] const autoReturnSummary = autoReturn && { status: autoReturn.status, returned: autoReturn.returned, pending: autoReturn.pending,