import { Request, Response } from 'express' import prisma from '../utils/prisma' import { successResponse, errorResponse } from '../utils/response' import { generateEquipmentCode, validateEquipmentCode } from '../utils/equipmentCode' import { calculateEquipmentValues, deriveParentBaseUnitPrice, refreshParentTotalValueWithChildren, sumBundleChildrenValue, syncMountedChildrenState } from '../utils/assetValue' import { getBorrowAnomalyMeta } from '../utils/borrowAnomaly' import { getEquipmentDeleteBlockedReason } from '../utils/equipmentDeletion' import { buildSyncedBusinessDepartmentWhere } from '../utils/organization' type EquipmentEntryMode = 'single' | 'parent' | 'child' interface EquipmentCreateInput { equipment_code?: string equipment_name?: string equipment_model?: string equipment_type?: string code_generation_mode?: 'auto' | 'manual' unit_price?: number | string total_quantity?: number | string remaining_quantity?: number | string purchase_date?: string | null supplier?: string | null description?: string | null storage_location_id?: number | string | null department_id?: number | string | null asset_type_id?: number | string | null status?: string } interface EquipmentBundleChildInput extends EquipmentCreateInput { quantity?: number | string | null notes?: string | null } const includeStorageLocation = { storageLocation: { select: { id: true, name: true, code: true, status: true } }, department: { select: { id: true, name: true, status: true } }, assetType: { select: { id: true, name: true, short_name: true, status: true } } } const EQUIPMENT_UPDATE_FIELD_LABELS: Record = { equipment_code: '资产编码', equipment_name: '资产名称', equipment_model: '资产型号', equipment_type: '资产类型', asset_type_id: '资产分类', unit_price: '单价', total_quantity: '库存总数量', purchase_date: '采购日期', supplier: '供应商', description: '资产描述', storage_location_id: '存放地址' } const buildEquipmentUpdateOperationDetails = ( currentEquipment: Record, updateData: Record ) => { const changedFields = Object.keys(EQUIPMENT_UPDATE_FIELD_LABELS).filter((field) => Object.prototype.hasOwnProperty.call(updateData, field) ) return `直接维护资产资料:${changedFields.map((field) => { const before = currentEquipment[field] ?? '-' const after = updateData[field] ?? '-' return `${EQUIPMENT_UPDATE_FIELD_LABELS[field]} ${before} → ${after}` }).join(';')}` } const activeBorrowSelect = { borrow_records: { where: { status: '已借出' as const }, orderBy: [{ borrow_time: 'desc' as const }, { id: 'desc' as const }], take: 1, select: { id: true, person_id: true, person_name: true, person_nickname: true, borrow_time: true, status: true, person: { select: { id: true, nickname: true, real_name: true, job_number: true } } } } } const EQUIPMENT_LIST_SORT_MODES = new Set(['created_desc', 'updated_desc', 'recent_change']) const includeEquipmentRelations = { ...includeStorageLocation, parent: { select: { id: true, equipment_code: true, equipment_name: true, equipment_model: true, unit_price: true } }, children: { select: { id: true, equipment_code: true, equipment_name: true, equipment_model: true, equipment_type: true, unit_price: true, status: true, mount_status: true, ...activeBorrowSelect } }, ...activeBorrowSelect } const loadRecursiveEquipmentDetail = async (rootId: number) => { const root = await prisma.equipment.findUnique({ where: { id: rootId }, include: { ...includeStorageLocation, parent: { select: { id: true, equipment_code: true, equipment_name: true, equipment_model: true, unit_price: true } }, ...activeBorrowSelect } }) if (!root) return null const all: any[] = [{ ...root, children: [] }] const visited = new Set([root.id]) let parentIds = [root.id] let depth = 0 while (parentIds.length > 0) { if (depth >= 100) { throw new Error('资产父子关系层级过深,请先检查资产关系') } const children = await prisma.equipment.findMany({ where: { parent_id: { in: parentIds } }, orderBy: { id: 'asc' }, include: { ...includeStorageLocation, parent: { select: { id: true, equipment_code: true, equipment_name: true, equipment_model: true, unit_price: true } }, ...activeBorrowSelect } }) if (children.length === 0) break const repeated = children.find((child) => visited.has(child.id)) if (repeated) { throw new Error(`资产 ${repeated.equipment_code} 存在循环父子关系,请先修复关系`) } children.forEach((child) => visited.add(child.id)) all.push(...children.map((child) => ({ ...child, children: [] }))) parentIds = children.map((child) => child.id) depth += 1 } const byId = new Map(all.map((item) => [item.id, item])) for (const item of all.slice(1)) { byId.get(item.parent_id)?.children.push(item) } return byId.get(root.id) } const getEquipmentBusinessHistoryCount = async (equipmentId: number, client: any = prisma) => { const counts = await Promise.all([ client.borrowRecord.count({ where: { equipment_id: equipmentId } }), client.maintenanceRecord.count({ where: { equipment_id: equipmentId } }), client.disposalRecord.count({ where: { equipment_id: equipmentId } }), client.disposalItem.count({ where: { equipment_id: equipmentId } }), client.inventoryTaskItem.count({ where: { equipment_id: equipmentId } }), client.assetTransferRecord.count({ where: { root_equipment_id: equipmentId } }), client.assetTransferItem.count({ where: { equipment_id: equipmentId } }), client.operationLog.count({ where: { equipment_id: equipmentId } }), client.mountHistory.count({ where: { OR: [ { child_id: equipmentId }, { parent_id: equipmentId }, { old_parent_id: equipmentId }, { new_parent_id: equipmentId } ] } }) ]) return counts.reduce((sum, count) => sum + count, 0) } const toOptionalNumber = (value: unknown) => { if (value === undefined || value === null || value === '') return null const numericValue = Number(value) return Number.isNaN(numericValue) ? null : numericValue } const mapCurrentBorrow = (borrowRecords: any[] | undefined) => { const record = borrowRecords?.[0] if (!record) { return null } return { id: record.id, person_id: record.person_id, person_name: record.person_name, person_nickname: record.person_nickname, borrow_time: record.borrow_time, status: record.status, person: record.person ? { id: record.person.id, nickname: record.person.nickname, real_name: record.person.real_name, job_number: record.person.job_number } : null } } const getLatestTimestamp = (...values: Array) => { return values.reduce((latest, value) => { if (!value) return latest const date = value instanceof Date ? value : new Date(value) if (Number.isNaN(date.getTime())) return latest if (!latest || date.getTime() > latest.getTime()) return date return latest }, null) } const serializeEquipmentListItem = (equipment: any) => { const children = Array.isArray(equipment.children) ? equipment.children.map((child: any) => { const { borrow_records, ...restChild } = child return { ...restChild, current_borrow: mapCurrentBorrow(borrow_records) } }) : [] const { borrow_records, ...restEquipment } = equipment const latestMountChangeAt = getLatestTimestamp( equipment.latest_parent_mount_change_at, equipment.latest_child_mount_change_at ) const recentChangeAt = getLatestTimestamp( equipment.recent_change_at, restEquipment.updated_at, ...children.map((child: any) => child.updated_at), latestMountChangeAt ) return { ...restEquipment, children, latest_mount_change_at: latestMountChangeAt, recent_change_at: recentChangeAt, current_borrow: mapCurrentBorrow(borrow_records), borrow_anomaly: getBorrowAnomalyMeta({ status: restEquipment.status, activeBorrowCount: Array.isArray(borrow_records) ? borrow_records.length : 0, totalQuantity: restEquipment.total_quantity, parentId: restEquipment.parent_id }) } } const normalizeEntryMode = (value: unknown): EquipmentEntryMode => { if (value === 'parent' || value === 'child') return value return 'single' } const ensureAdministrativeCreateAllowed = (req: Request, entryMode: EquipmentEntryMode) => { if (req.res?.locals.user?.role !== 'administrative') { return } if (Array.isArray(req.body.children) && req.body.children.length > 0) { throw new Error('行政角色不能在登记时建立父子资产关系,请由 IT 登记后单独挂载') } if (req.body.department_id !== undefined && req.body.department_id !== null && req.body.department_id !== '') { throw new Error('行政角色登记资产时不能直接分配部门') } if (req.body.status && req.body.status !== '可用') { throw new Error('行政角色登记资产时只能登记为可用状态') } } const ensureAdministrativeCorrectionAllowed = async ( req: Request, equipment: any, client: any = prisma, role?: string ) => { if ((role || req.res?.locals.user?.role) !== 'administrative') { return } const forbiddenFields = ['status', 'department_id', 'parent_id', 'mount_status', 'remaining_quantity'] const changedForbiddenField = forbiddenFields.find((field) => Object.prototype.hasOwnProperty.call(req.body, field) ) if (changedForbiddenField) { throw new Error('行政角色只能纠错基础资料,不能直接修改状态、部门或父子关系') } if (equipment.status !== '可用') { throw new Error('行政角色只能纠错处于可用状态的资产') } const [borrowCount, maintenanceCount, disposalCount] = await Promise.all([ client.borrowRecord.count({ where: { equipment_id: equipment.id, status: '已借出' } }), client.maintenanceRecord.count({ where: { equipment_id: equipment.id, status: 'in_progress' } }), client.disposalItem.count({ where: { equipment_id: equipment.id, disposal: { status: { in: ['pending', 'approved'] } } } }) ]) if (borrowCount > 0 || maintenanceCount > 0 || disposalCount > 0) { throw new Error('资产存在进行中的借用、维修或报废业务,行政角色不能纠错') } } const ensureEquipmentCodeHasNoBusinessHistory = async (equipmentId: number, client: any = prisma) => { if (await getEquipmentBusinessHistoryCount(equipmentId, client) > 0) { throw new Error('资产已有业务历史,不能修改资产编码') } } const EDIT_LOCKED_STATUSES = new Set(['维护中', '待报废', '已报废', '已损坏']) const resolveEditableEquipmentStatus = ({ currentStatus, requestedStatus, remainingQuantity }: { currentStatus: string requestedStatus?: unknown remainingQuantity: number }) => { const normalizedRequestedStatus = typeof requestedStatus === 'string' && requestedStatus.trim() ? requestedStatus.trim() : undefined const autoDerivedStatus = remainingQuantity > 0 ? '可用' : '已借出' if (EDIT_LOCKED_STATUSES.has(currentStatus)) { return currentStatus } if (normalizedRequestedStatus && EDIT_LOCKED_STATUSES.has(normalizedRequestedStatus)) { return autoDerivedStatus } return normalizedRequestedStatus || autoDerivedStatus } const ensureLocationExists = async (client: any, locationId?: number | null) => { if (!locationId) { throw new Error('地址信息不能为空') } const location = await client.storageLocation.findUnique({ where: { id: locationId } }) if (!location || location.status !== 'active') { throw new Error('所选地址不存在或已停用') } return location } const ensureAssetTypeExists = async (client: any, equipmentType?: string, assetTypeId?: number | null) => { const normalizedEquipmentType = equipmentType?.trim() const assetType = assetTypeId ? await client.assetType.findUnique({ where: { id: assetTypeId } }) : normalizedEquipmentType ? await client.assetType.findFirst({ where: { name: normalizedEquipmentType } }) : null if (!assetType || assetType.status !== 'active') { throw new Error(`资产类型 "${normalizedEquipmentType || assetTypeId || ''}" 不存在或已停用`) } if (normalizedEquipmentType && assetType.name !== normalizedEquipmentType) { throw new Error('资产类型信息不匹配,请重新选择后再保存') } return assetType } const ensureUpdateAssetTypeExists = async ( client: any, equipmentType?: string, assetTypeId?: number | null ) => { try { return await ensureAssetTypeExists(client, equipmentType, assetTypeId) } catch (error: any) { error.statusCode = 422 throw error } } const ensureAssetTypeSupportsCurrentRelation = ( assetType: { can_be_parent: boolean; can_be_child: boolean }, parentId: number | null, childCount: number ) => { if (parentId && !assetType.can_be_child) { const error: any = new Error('当前资产已挂载在父资产下,新类型必须允许作为子资产') error.statusCode = 422 throw error } if (childCount > 0 && !assetType.can_be_parent) { const error: any = new Error('当前资产仍挂载子资产,新类型必须允许作为父资产') error.statusCode = 422 throw error } } const ensureBusinessDepartmentExists = async (client: any, departmentId?: number | null) => { if (!departmentId) { return null } const department = await client.department.findFirst({ where: { id: departmentId, status: 'active', ...buildSyncedBusinessDepartmentWhere() }, select: { id: true, name: true } }) if (!department) { throw new Error('所选使用部门不存在或已停用') } return department } const resolveEquipmentCode = async ( client: any, codeGenerationMode: 'auto' | 'manual', equipmentCode: string | undefined, equipmentType: string, locationId?: number | null ) => { if (codeGenerationMode === 'auto') { let finalCode = await generateEquipmentCode(equipmentType, client, locationId) const existingCheck = await client.equipment.findUnique({ where: { equipment_code: finalCode } }) if (existingCheck) { finalCode = await generateEquipmentCode(equipmentType, client, locationId) } return finalCode } if (!equipmentCode?.trim()) { throw new Error('自定义录入模式下资产编码不能为空') } const normalizedCode = equipmentCode.trim().toUpperCase() if (!validateEquipmentCode(normalizedCode)) { throw new Error('资产编码格式不正确') } const existing = await client.equipment.findUnique({ where: { equipment_code: normalizedCode } }) if (existing) { throw new Error('资产编码已存在') } return normalizedCode } const createEquipmentRecord = async ( client: any, input: EquipmentCreateInput, options?: { forceSingleQuantity?: boolean parentId?: number | null mountStatus?: 'none' | 'mounted' | 'unmounted' } ) => { const equipmentName = input.equipment_name?.trim() if (!equipmentName) { throw new Error('资产名称不能为空') } const locationId = toOptionalNumber(input.storage_location_id) const departmentId = toOptionalNumber(input.department_id) const assetTypeId = toOptionalNumber(input.asset_type_id) await ensureLocationExists(client, locationId) await ensureBusinessDepartmentExists(client, departmentId) const assetType = await ensureAssetTypeExists(client, input.equipment_type, assetTypeId) const codeGenerationMode = input.code_generation_mode === 'manual' ? 'manual' : 'auto' const finalCode = await resolveEquipmentCode( client, codeGenerationMode, input.equipment_code, assetType.name, locationId ) const finalTotalQuantity = options?.forceSingleQuantity ? 1 : Math.max(1, Number(input.total_quantity) || 1) const requestedRemainingQuantity = options?.forceSingleQuantity ? 1 : Number(input.remaining_quantity ?? finalTotalQuantity) || finalTotalQuantity const remainingQuantity = Math.min(finalTotalQuantity, Math.max(0, requestedRemainingQuantity)) const unitPrice = Number(input.unit_price) || 0 const finalStatus = input.status || '可用' const values = calculateEquipmentValues({ unitPrice, totalQuantity: finalTotalQuantity, remainingQuantity, status: finalStatus }) return client.equipment.create({ data: { equipment_code: finalCode, equipment_name: equipmentName, equipment_model: input.equipment_model?.trim() || null, equipment_type: assetType.name, code_generation_mode: codeGenerationMode, unit_price: unitPrice, total_quantity: finalTotalQuantity, remaining_quantity: remainingQuantity, total_value: values.total_value, borrowed_value: values.borrowed_value, available_value: values.available_value, purchase_date: input.purchase_date ? new Date(input.purchase_date) : null, supplier: input.supplier?.trim() || null, description: input.description?.trim() || null, status: finalStatus, storage_location_id: locationId || undefined, department_id: departmentId || undefined, asset_type_id: assetType.id, parent_id: options?.parentId || null, mount_status: options?.mountStatus || 'none' } }) } // 获取设备列表 export const getEquipmentList = async (req: Request, res: Response) => { try { const { page = 1, pageSize = 10, equipmentType, status, keyword, storage_location_id, department_id, asset_type_id, mount_status, parent_id, sort } = req.query const where: any = {} const hasParentFilter = !Number.isNaN(Number(parent_id)) && Boolean(parent_id) const sortMode = typeof sort === 'string' && EQUIPMENT_LIST_SORT_MODES.has(sort) ? sort : 'created_desc' if (equipmentType) { where.equipment_type = equipmentType } if (status) { where.status = status } if (keyword) { const normalizedKeyword = String(keyword).trim() const ownSearchConditions = [ { equipment_name: { contains: normalizedKeyword } }, { equipment_code: { contains: normalizedKeyword } }, { equipment_model: { contains: normalizedKeyword } }, { department: { is: { name: { contains: normalizedKeyword } } } }, { storageLocation: { is: { name: { contains: normalizedKeyword } } } }, { borrow_records: { some: { status: '已借出', OR: [ { person_nickname: { contains: normalizedKeyword } }, { person_name: { contains: normalizedKeyword } }, { person: { is: { nickname: { contains: normalizedKeyword } } } }, { person: { is: { real_name: { contains: normalizedKeyword } } } }, { person: { is: { job_number: { contains: normalizedKeyword } } } } ] } } } ] where.OR = hasParentFilter ? ownSearchConditions : [ ...ownSearchConditions, { children: { some: { OR: ownSearchConditions } } } ] } const locationId = Number(storage_location_id) if (!Number.isNaN(locationId) && storage_location_id) { where.storage_location_id = locationId } const deptId = Number(department_id) if (!Number.isNaN(deptId) && department_id) { where.department_id = deptId } const typeId = Number(asset_type_id) if (!Number.isNaN(typeId) && asset_type_id) { where.asset_type_id = typeId } // 挂载状态筛选 if (mount_status && mount_status !== 'all') { if (hasParentFilter) { if (mount_status === 'mounted') { where.mount_status = 'mounted' } else if (mount_status === 'unmounted') { where.mount_status = { in: ['none', 'unmounted'] } } } else if (mount_status === 'mounted') { where.children = { some: {} } } else if (mount_status === 'unmounted') { where.children = { none: {} } } } // 父资产筛选(显示某主机的所有配件) const parentIdNum = Number(parent_id) if (hasParentFilter) { where.parent_id = parentIdNum } else { where.parent_id = null } const skip = (Number(page) - 1) * Number(pageSize) const take = Number(pageSize) const listInclude = { ...includeStorageLocation, ...activeBorrowSelect, parent: { select: { id: true, equipment_code: true, equipment_name: true } }, children: { select: { id: true, equipment_code: true, equipment_name: true, equipment_model: true, equipment_type: true, unit_price: true, status: true, mount_status: true, updated_at: true, ...activeBorrowSelect } } } let list: any[] = [] let total = 0 if (sortMode === 'recent_change') { const candidates = await prisma.equipment.findMany({ where, select: { id: true, updated_at: true, children: { select: { updated_at: true } } } }) total = candidates.length const candidateIds = candidates.map((item) => item.id) const candidateLatestChange = new Map() for (const candidate of candidates) { candidateLatestChange.set( candidate.id, getLatestTimestamp( candidate.updated_at, ...candidate.children.map((child) => child.updated_at) ) ) } if (candidateIds.length > 0) { const groupedHistory = hasParentFilter ? await prisma.mountHistory.groupBy({ by: ['child_id'], where: { child_id: { in: candidateIds } }, _max: { operated_at: true } }) : await prisma.mountHistory.groupBy({ by: ['parent_id'], where: { parent_id: { in: candidateIds } }, _max: { operated_at: true } }) for (const item of groupedHistory) { const targetId = hasParentFilter ? (item as any).child_id : (item as any).parent_id if (!targetId) continue candidateLatestChange.set( targetId, getLatestTimestamp(candidateLatestChange.get(targetId), item._max.operated_at) ) } } const pageIds = [...candidateIds] .sort((leftId, rightId) => { const leftTime = candidateLatestChange.get(leftId)?.getTime() || 0 const rightTime = candidateLatestChange.get(rightId)?.getTime() || 0 return rightTime - leftTime || rightId - leftId }) .slice(skip, skip + take) if (pageIds.length > 0) { const pageIdOrder = new Map(pageIds.map((id, index) => [id, index])) const pageList = await prisma.equipment.findMany({ where: { id: { in: pageIds } }, include: listInclude }) list = pageList .map((item) => ({ ...item, recent_change_at: candidateLatestChange.get(item.id) || null })) .sort((left, right) => (pageIdOrder.get(left.id) || 0) - (pageIdOrder.get(right.id) || 0)) } } else { const orderBy = sortMode === 'updated_desc' ? [{ updated_at: 'desc' as const }, { id: 'desc' as const }] : [{ created_at: 'desc' as const }, { id: 'desc' as const }] ;[list, total] = await Promise.all([ prisma.equipment.findMany({ where, skip, take, orderBy, include: listInclude }), prisma.equipment.count({ where }) ]) } successResponse( res, { list: list.map(serializeEquipmentListItem), total, page: Number(page), pageSize: Number(pageSize) }, '获取成功' ) } catch (error: any) { errorResponse(res, error.message || '获取资产列表失败') } } // 获取资产详情 export const getEquipmentDetail = async (req: Request, res: Response) => { try { const { id } = req.params const equipment = await loadRecursiveEquipmentDetail(Number(id)) if (!equipment) { return errorResponse(res, '资产不存在', 404) } const businessHistoryCount = await getEquipmentBusinessHistoryCount(equipment.id) successResponse(res, { ...equipment, can_correct_code: businessHistoryCount === 0 }, '获取成功') } catch (error: any) { errorResponse(res, error.message || '获取资产详情失败') } } export const getEquipmentTransferHistory = async (req: Request, res: Response) => { try { const equipmentId = Number(req.params.id) const history = await prisma.assetTransferRecord.findMany({ where: { OR: [ { root_equipment_id: equipmentId }, { items: { some: { equipment_id: equipmentId } } } ] }, orderBy: { operated_at: 'desc' }, include: { operator: { select: { id: true, name: true, username: true } }, items: { orderBy: { id: 'asc' } } } }) successResponse(res, history, '获取成功') } catch (error: any) { errorResponse(res, error.message || '获取资产流转历史失败') } } // 新增资产 export const createEquipment = async (req: Request, res: Response) => { try { const entryMode = normalizeEntryMode(req.body.entry_mode) ensureAdministrativeCreateAllowed(req, entryMode) const userId = Number(res.locals.user?.id) const locationId = toOptionalNumber(req.body.storage_location_id) const departmentId = toOptionalNumber(req.body.department_id) const assetTypeId = toOptionalNumber(req.body.asset_type_id) const bundleChildren = Array.isArray(req.body.children) ? (req.body.children as EquipmentBundleChildInput[]) : [] const createdEquipment = await prisma.$transaction(async (tx) => { if (entryMode === 'parent') { if (!Number.isFinite(userId) || userId <= 0) { throw new Error('用户未登录,无法创建父子资产') } const parentAssetType = await ensureAssetTypeExists(tx, req.body.equipment_type, assetTypeId) if (!parentAssetType.can_be_parent) { throw new Error('当前资产类型不能作为父资产') } const bundleChildrenTotalValue = sumBundleChildrenValue(bundleChildren) const parentBaseUnitPrice = deriveParentBaseUnitPrice(req.body.unit_price, bundleChildrenTotalValue) const parent = await createEquipmentRecord( tx, { ...req.body, unit_price: parentBaseUnitPrice, storage_location_id: locationId, department_id: departmentId, asset_type_id: parentAssetType.id }, { forceSingleQuantity: true, mountStatus: 'none' } ) for (let index = 0; index < bundleChildren.length; index += 1) { const childInput = bundleChildren[index] const childName = childInput.equipment_name?.trim() const childType = childInput.equipment_type?.trim() const childQuantity = Math.max(1, Math.floor(Number(childInput.quantity) || 1)) const hasAnyValue = Boolean( childName || childType || childInput.equipment_model?.trim() || childInput.description?.trim() || childInput.notes?.trim() || childQuantity > 1 || Number(childInput.unit_price || 0) ) if (!hasAnyValue) { continue } if (!childName || !childType) { throw new Error(`第 ${index + 1} 个子资产还没填写完整`) } const childAssetType = await ensureAssetTypeExists( tx, childType, toOptionalNumber(childInput.asset_type_id) ) if (!childAssetType.can_be_child) { throw new Error(`子资产类型 "${childAssetType.name}" 不能作为配件挂载`) } for (let quantityIndex = 0; quantityIndex < childQuantity; quantityIndex += 1) { const child = await createEquipmentRecord( tx, { ...childInput, purchase_date: childInput.purchase_date ?? req.body.purchase_date, supplier: childInput.supplier ?? req.body.supplier, storage_location_id: locationId, department_id: departmentId, asset_type_id: childAssetType.id }, { forceSingleQuantity: true, parentId: parent.id, mountStatus: 'mounted' } ) await tx.mountHistory.create({ data: { child_id: child.id, parent_id: parent.id, operation_type: 'mount', operated_by: userId, notes: childInput.notes?.trim() || '创建父资产时自动挂载' } }) } } await refreshParentTotalValueWithChildren(tx, parent.id) return parent } if (entryMode === 'child') { const childAssetType = await ensureAssetTypeExists(tx, req.body.equipment_type, assetTypeId) if (!childAssetType.can_be_child) { throw new Error('当前资产类型不能作为子资产') } return createEquipmentRecord( tx, { ...req.body, storage_location_id: locationId, department_id: departmentId, asset_type_id: childAssetType.id }, { forceSingleQuantity: true, mountStatus: 'none' } ) } return createEquipmentRecord( tx, { ...req.body, storage_location_id: locationId, department_id: departmentId, asset_type_id: assetTypeId }, { forceSingleQuantity: false, mountStatus: 'none' } ) }) const equipment = await prisma.equipment.findUnique({ where: { id: createdEquipment.id }, include: includeEquipmentRelations }) successResponse(res, equipment, '新增成功') } catch (error: any) { if (error.code === 'P2002' || error.message?.includes('资产编码已存在')) { return errorResponse(res, '资产编码已存在') } const statusCode = error.message?.includes('不存在') || error.message?.includes('不能为空') || error.message?.includes('格式不正确') || error.message?.includes('不能作为') || error.message?.includes('填写完整') ? 422 : 500 errorResponse(res, error.message || '新增资产失败', statusCode) } } // 更新资产 export const updateEquipment = async (req: Request, res: Response) => { try { const { id } = req.params const { equipment_code, equipment_name, equipment_model, equipment_type, unit_price, total_quantity, status, purchase_date, supplier, description, storage_location_id, department_id, asset_type_id } = req.body // 获取当前设备信息 const currentEquipment = await prisma.equipment.findUnique({ where: { id: Number(id) } }) if (!currentEquipment) { return errorResponse(res, '资产不存在', 404) } const controlledFields = ['status', 'department_id', 'parent_id', 'mount_status', 'remaining_quantity'] const submittedControlledField = controlledFields.find((field) => Object.prototype.hasOwnProperty.call(req.body, field) ) if (submittedControlledField) { return errorResponse( res, '状态、部门、剩余数量和父子关系必须通过正式业务流程变更', 422 ) } const currentRole = res.locals.user?.role as string | undefined await ensureAdministrativeCorrectionAllowed(req, currentEquipment, prisma, currentRole) let normalizedEquipmentCode = currentEquipment.equipment_code if (equipment_code !== undefined && equipment_code !== currentEquipment.equipment_code) { normalizedEquipmentCode = String(equipment_code).trim().toUpperCase() if (!validateEquipmentCode(normalizedEquipmentCode)) { return errorResponse(res, '资产编码格式不正确', 422) } await ensureEquipmentCodeHasNoBusinessHistory(currentEquipment.id) const duplicate = await prisma.equipment.findUnique({ where: { equipment_code: normalizedEquipmentCode }, select: { id: true } }) if (duplicate && duplicate.id !== currentEquipment.id) { return errorResponse(res, '资产编码已存在', 409) } } let targetLocationId = currentEquipment.storage_location_id if (storage_location_id !== undefined) { const normalizedLocationId = Number(storage_location_id) try { await ensureLocationExists(prisma, normalizedLocationId) } catch (error: any) { return errorResponse(res, error.message || '地址无效', 422) } targetLocationId = normalizedLocationId } // 处理部门ID let targetDeptId = currentEquipment.department_id if (department_id !== undefined) { targetDeptId = department_id ? Number(department_id) : null } await ensureBusinessDepartmentExists(prisma, targetDeptId) // 资产类型名称与外键必须成对更新,并且不能破坏已有父子关系的类型能力。 const assetTypeChangeRequested = Object.prototype.hasOwnProperty.call(req.body, 'equipment_type') || Object.prototype.hasOwnProperty.call(req.body, 'asset_type_id') let targetTypeId = currentEquipment.asset_type_id let targetEquipmentType = currentEquipment.equipment_type if (assetTypeChangeRequested) { let requestedTypeId: number | null = null if (asset_type_id !== undefined && asset_type_id !== null && asset_type_id !== '') { requestedTypeId = Number(asset_type_id) if (!Number.isInteger(requestedTypeId) || requestedTypeId <= 0) { return errorResponse(res, '资产类型参数不合法', 422) } } else if (equipment_type === undefined) { requestedTypeId = currentEquipment.asset_type_id } const requestedTypeName = equipment_type === undefined ? currentEquipment.equipment_type : String(equipment_type).trim() const resolvedAssetType = await ensureUpdateAssetTypeExists( prisma, requestedTypeName, requestedTypeId ) const currentChildCount = await prisma.equipment.count({ where: { parent_id: currentEquipment.id } }) ensureAssetTypeSupportsCurrentRelation( resolvedAssetType, currentEquipment.parent_id, currentChildCount ) targetTypeId = resolvedAssetType.id targetEquipmentType = resolvedAssetType.name } // 计算价值与剩余库存同步逻辑 const finalTotalQuantity = total_quantity !== undefined ? Number(total_quantity) : currentEquipment.total_quantity if ( total_quantity !== undefined && (!Number.isInteger(finalTotalQuantity) || finalTotalQuantity < 1) ) { return errorResponse(res, '资产总数量必须是大于或等于 1 的整数', 422) } const finalUnitPrice = unit_price !== undefined ? Number(unit_price) : Number(currentEquipment.unit_price) // 已借数量 = 原总数 - 原剩余数(保证不为负) const borrowedQuantity = Math.max(currentEquipment.total_quantity - currentEquipment.remaining_quantity, 0) // 若修改了总库存,则根据已借数量同步计算新的剩余库存;否则保持原剩余库存 const newRemainingQuantity = total_quantity !== undefined ? Math.max(finalTotalQuantity - borrowedQuantity, 0) : currentEquipment.remaining_quantity const resolvedStatus = resolveEditableEquipmentStatus({ currentStatus: currentEquipment.status, requestedStatus: status, remainingQuantity: newRemainingQuantity }) if (currentRole === 'administrative' && resolvedStatus !== '可用') { return errorResponse( res, '该数量纠错会改变资产可用状态,请先核对数量或由管理员处理', 422 ) } const values = calculateEquipmentValues({ unitPrice: finalUnitPrice, totalQuantity: finalTotalQuantity, remainingQuantity: newRemainingQuantity, status: resolvedStatus }) // 基础资料纠错只写入本次明确提交的字段,避免把读取时的部门、状态等快照再次全量覆盖。 const correctionUpdateData: Record = {} const assignIfSubmitted = (field: string, value: unknown) => { if (Object.prototype.hasOwnProperty.call(req.body, field)) { correctionUpdateData[field] = value } } assignIfSubmitted('equipment_name', equipment_name) assignIfSubmitted('equipment_model', equipment_model) assignIfSubmitted('supplier', supplier) assignIfSubmitted('description', description) if (assetTypeChangeRequested) { correctionUpdateData.equipment_type = targetEquipmentType correctionUpdateData.asset_type_id = targetTypeId } if (Object.prototype.hasOwnProperty.call(req.body, 'equipment_code')) { correctionUpdateData.equipment_code = normalizedEquipmentCode if (normalizedEquipmentCode !== currentEquipment.equipment_code) { correctionUpdateData.code_generation_mode = 'manual' } } if (Object.prototype.hasOwnProperty.call(req.body, 'purchase_date') && purchase_date) { correctionUpdateData.purchase_date = new Date(purchase_date) } if (Object.prototype.hasOwnProperty.call(req.body, 'storage_location_id')) { correctionUpdateData.storage_location_id = targetLocationId } if (Object.prototype.hasOwnProperty.call(req.body, 'unit_price')) { correctionUpdateData.unit_price = finalUnitPrice correctionUpdateData.total_value = values.total_value correctionUpdateData.borrowed_value = values.borrowed_value correctionUpdateData.available_value = values.available_value } if (Object.prototype.hasOwnProperty.call(req.body, 'total_quantity')) { correctionUpdateData.total_quantity = finalTotalQuantity correctionUpdateData.remaining_quantity = newRemainingQuantity correctionUpdateData.status = resolvedStatus correctionUpdateData.total_value = values.total_value correctionUpdateData.borrowed_value = values.borrowed_value correctionUpdateData.available_value = values.available_value } const updateData = correctionUpdateData if (Object.keys(updateData).length === 0) { const unchangedEquipment = await prisma.equipment.findUnique({ where: { id: Number(id) }, include: includeStorageLocation }) return successResponse(res, unchangedEquipment, '无需更新') } const updated = await prisma.$transaction(async (tx) => { await tx.$queryRawUnsafe( `SELECT id FROM equipment WHERE id = ${currentEquipment.id} FOR UPDATE` ) await ensureAdministrativeCorrectionAllowed(req, currentEquipment, tx, currentRole) if (assetTypeChangeRequested) { const resolvedAssetType = await ensureUpdateAssetTypeExists( tx, targetEquipmentType, targetTypeId ) const currentChildCount = await tx.equipment.count({ where: { parent_id: currentEquipment.id } }) ensureAssetTypeSupportsCurrentRelation( resolvedAssetType, currentEquipment.parent_id, currentChildCount ) } if (normalizedEquipmentCode !== currentEquipment.equipment_code) { await ensureEquipmentCodeHasNoBusinessHistory(currentEquipment.id, tx) const duplicate = await tx.equipment.findUnique({ where: { equipment_code: normalizedEquipmentCode }, select: { id: true } }) if (duplicate && duplicate.id !== currentEquipment.id) { const duplicateError: any = new Error('资产编码已存在') duplicateError.statusCode = 409 throw duplicateError } } const claimed = await tx.equipment.updateMany({ where: { id: Number(id), status: currentEquipment.status, department_id: currentEquipment.department_id, parent_id: currentEquipment.parent_id, remaining_quantity: currentEquipment.remaining_quantity, updated_at: currentEquipment.updated_at }, data: updateData }) if (claimed.count !== 1) { return false } const childCount = await tx.equipment.count({ 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)) } if (currentEquipment.parent_id) { await refreshParentTotalValueWithChildren(tx, currentEquipment.parent_id) } const operator = res.locals.user await tx.operationLog.create({ data: { user_id: operator?.id || null, username: operator?.username || operator?.name || '未知用户', operation_type: 'asset_basic_update', equipment_id: currentEquipment.id, equipment_code: currentEquipment.equipment_code, operation_details: buildEquipmentUpdateOperationDetails(currentEquipment, updateData), ip_address: req.ip || null } }) return true }) if (!updated) { return errorResponse(res, '资产状态、部门或挂载关系已变化,请刷新后重试', 409) } const equipment = await prisma.equipment.findUnique({ where: { id: Number(id) }, include: includeStorageLocation }) successResponse(res, equipment, '更新成功') } catch (error: any) { const statusCode = error.statusCode || (error.code === 'P2002' ? 409 : 400) errorResponse(res, error.message || '更新资产失败', statusCode) } } // 删除资产 export const deleteEquipment = async (req: Request, res: Response) => { try { const { id } = req.params const equipmentId = Number(id) const equipment = await prisma.equipment.findUnique({ where: { id: equipmentId }, include: { _count: { select: { borrow_records: true, children: true, mountHistories: true, disposalRecords: true, disposalItems: true, maintenanceRecords: true, inventoryTaskItems: true, transferRootRecords: true, transferItems: true } } } }) if (!equipment) { return errorResponse(res, '资产不存在', 404) } const [relatedMountHistoryCount, operationLogCount] = await Promise.all([ prisma.mountHistory.count({ where: { OR: [ { child_id: equipmentId }, { parent_id: equipmentId }, { old_parent_id: equipmentId }, { new_parent_id: equipmentId } ] } }), prisma.operationLog.count({ where: { equipment_id: equipmentId } }) ]) const blockedReason = getEquipmentDeleteBlockedReason({ borrowRecordCount: equipment._count.borrow_records, isMountedChild: Boolean(equipment.parent_id), childCount: equipment._count.children, mountHistoryCount: relatedMountHistoryCount, disposalRecordCount: equipment._count.disposalRecords, disposalItemCount: equipment._count.disposalItems, maintenanceRecordCount: equipment._count.maintenanceRecords, inventoryTaskItemCount: equipment._count.inventoryTaskItems, transferHistoryCount: equipment._count.transferRootRecords + equipment._count.transferItems, operationLogCount }) if (blockedReason) { return errorResponse(res, blockedReason) } await prisma.$transaction(async (tx) => { await tx.equipment.delete({ where: { id: equipmentId } }) }) successResponse(res, null, '删除成功') } catch (error: any) { if (error.code === 'P2025') { return errorResponse(res, '资产不存在', 404) } errorResponse(res, error.message || '删除资产失败') } } // 生成资产编码 export const generateCode = async (req: Request, res: Response) => { try { const { equipment_type, code_generation_mode = 'auto', storage_location_id } = req.body if (code_generation_mode === 'auto') { const locationId = storage_location_id ? Number(storage_location_id) : null const code = await generateEquipmentCode(equipment_type, prisma, locationId) successResponse(res, { equipment_code: code, code_format: 'JS-{类型简称}-{序号(4位)}' }, '生成成功') } else { errorResponse(res, '自定义录入模式不需要生成编码') } } catch (error: any) { errorResponse(res, error.message || '生成编码失败') } } // 验证资产编码 export const verifyCode = async (req: Request, res: Response) => { try { const { equipment_code } = req.body if (!validateEquipmentCode(equipment_code)) { return successResponse(res, { is_valid: false, is_unique: false, message: '编码格式不正确' }, '验证成功') } const existing = await prisma.equipment.findUnique({ where: { equipment_code } }) if (existing) { return successResponse(res, { is_valid: true, is_unique: false, message: '编码已存在' }, '验证成功') } successResponse(res, { is_valid: true, is_unique: true, message: '编码可用' }, '验证成功') } catch (error: any) { errorResponse(res, error.message || '验证编码失败') } } // 根据资产编码查询资产信息(扫码) export const scanEquipment = async (req: Request, res: Response) => { try { const { equipment_code } = req.params const equipment = await prisma.equipment.findUnique({ where: { equipment_code }, include: includeStorageLocation }) if (!equipment) { return errorResponse(res, '资产不存在', 404) } const is_available = equipment.status === '可用' && equipment.remaining_quantity > 0 successResponse(res, { ...equipment, is_available, message: is_available ? '资产可用' : '资产不可用' }, '查询成功') } catch (error: any) { errorResponse(res, error.message || '查询资产失败') } }