623 lines
20 KiB
TypeScript
623 lines
20 KiB
TypeScript
import { Request, Response } from 'express'
|
|
import { Prisma } from '@prisma/client'
|
|
import prisma from '../utils/prisma'
|
|
import { successResponse, errorResponse } from '../utils/response'
|
|
import {
|
|
calculateEquipmentValues,
|
|
calculateChildrenTotalValueFromRecords,
|
|
calculateCurrentTotalValueWithChildren,
|
|
refreshParentTotalValueWithChildren
|
|
} from '../utils/assetValue'
|
|
import {
|
|
getAssetTreeFingerprint,
|
|
loadAssetTree,
|
|
lockEquipmentRows,
|
|
type AssetTreeItem
|
|
} from '../services/assetMovementService'
|
|
|
|
type TransactionClient = Prisma.TransactionClient
|
|
type MountLifecycleStatus = '可用' | '已借出' | '维护中' | '待报废' | '已报废'
|
|
|
|
const PARENT_MOUNTABLE_STATUSES = new Set<MountLifecycleStatus>(['可用', '已借出'])
|
|
|
|
class MountOperationError extends Error {
|
|
statusCode: number
|
|
|
|
constructor(message: string, statusCode: number = 422) {
|
|
super(message)
|
|
this.name = 'MountOperationError'
|
|
this.statusCode = statusCode
|
|
}
|
|
}
|
|
|
|
const ensureParentMountOperable = (equipment: { status: string }, label: string) => {
|
|
if (equipment.status === '维护中') {
|
|
throw new MountOperationError(`${label}正在维修,请先完成或取消维修后再挂载或卸载配件`, 409)
|
|
}
|
|
if (!PARENT_MOUNTABLE_STATUSES.has(equipment.status as MountLifecycleStatus)) {
|
|
throw new MountOperationError(`${label}当前状态不可挂载或更换配件`)
|
|
}
|
|
}
|
|
|
|
const resolveDetachedChildStatus = (status?: string): MountLifecycleStatus => {
|
|
const normalized = (status || '').trim()
|
|
if (!normalized) {
|
|
return '可用'
|
|
}
|
|
|
|
if (normalized !== '可用') {
|
|
throw new MountOperationError('拆下的配件只能恢复为可用;维修或报废请使用正式业务流程')
|
|
}
|
|
|
|
return '可用'
|
|
}
|
|
|
|
const buildEquipmentStateUpdate = (
|
|
equipment: { unit_price: unknown; total_quantity: number; status: string },
|
|
targetStatus: MountLifecycleStatus
|
|
) => {
|
|
const totalQuantity = Math.max(1, Number(equipment.total_quantity) || 1)
|
|
const remainingQuantity = targetStatus === '已借出' ? 0 : totalQuantity
|
|
const values = calculateEquipmentValues({
|
|
unitPrice: Number(equipment.unit_price) || 0,
|
|
totalQuantity,
|
|
remainingQuantity,
|
|
status: targetStatus
|
|
})
|
|
|
|
return {
|
|
status: targetStatus,
|
|
remaining_quantity: remainingQuantity,
|
|
total_value: values.total_value,
|
|
borrowed_value: values.borrowed_value,
|
|
available_value: values.available_value
|
|
}
|
|
}
|
|
|
|
const resolveMountedChildStatus = (parent: { status: string }): MountLifecycleStatus => {
|
|
return parent.status === '已借出' || parent.status === '维护中'
|
|
? (parent.status as MountLifecycleStatus)
|
|
: '可用'
|
|
}
|
|
|
|
const ensureAssetTreeAttachable = async (
|
|
client: TransactionClient,
|
|
items: AssetTreeItem[],
|
|
label: string
|
|
) => {
|
|
const blocked = items.find((item) => item.status !== '可用' || item.remaining_quantity <= 0)
|
|
if (blocked) {
|
|
throw new MountOperationError(`${label}中的资产 ${blocked.equipment_code} 当前状态不可挂载`)
|
|
}
|
|
const activeBorrowCount = await client.borrowRecord.count({
|
|
where: {
|
|
equipment_id: { in: items.map((item) => item.id) },
|
|
status: '已借出'
|
|
}
|
|
})
|
|
if (activeBorrowCount > 0) {
|
|
throw new MountOperationError(`${label}存在未归还记录,当前不可挂载`)
|
|
}
|
|
}
|
|
|
|
const updateAssetTreeState = async (
|
|
client: TransactionClient,
|
|
items: AssetTreeItem[],
|
|
input: {
|
|
rootParentId: number | null
|
|
rootMountStatus: 'mounted' | 'unmounted'
|
|
targetStatus: MountLifecycleStatus
|
|
departmentId: number | null
|
|
}
|
|
) => {
|
|
const rootId = items[0]?.id
|
|
for (const item of items) {
|
|
const isRoot = item.id === rootId
|
|
const claimed = await client.equipment.updateMany({
|
|
where: {
|
|
id: item.id,
|
|
parent_id: item.parent_id,
|
|
department_id: item.department_id,
|
|
status: item.status,
|
|
mount_status: item.mount_status,
|
|
remaining_quantity: item.remaining_quantity,
|
|
updated_at: item.updated_at
|
|
},
|
|
data: {
|
|
...(isRoot
|
|
? {
|
|
parent_id: input.rootParentId,
|
|
mount_status: input.rootMountStatus
|
|
}
|
|
: {}),
|
|
department_id: input.departmentId,
|
|
...buildEquipmentStateUpdate(item, input.targetStatus)
|
|
}
|
|
})
|
|
if (claimed.count !== 1) {
|
|
throw new MountOperationError(`资产 ${item.equipment_code} 状态或挂载关系已变化,请刷新后重试`, 409)
|
|
}
|
|
}
|
|
}
|
|
|
|
const loadMountAncestors = async (
|
|
client: TransactionClient,
|
|
parentId: number,
|
|
attachingChildId?: number
|
|
) => {
|
|
if (parentId === attachingChildId) {
|
|
throw new MountOperationError('父资产和子资产不能是同一条记录')
|
|
}
|
|
|
|
const visited = new Set<number>()
|
|
let currentId: number | null = parentId
|
|
for (let depth = 0; currentId !== null; depth += 1) {
|
|
if (depth >= 100) {
|
|
throw new MountOperationError('资产父子关系层级过深,请先检查资产关系', 409)
|
|
}
|
|
if (currentId === attachingChildId) {
|
|
throw new MountOperationError('不能把资产挂载到自己的下级节点上')
|
|
}
|
|
if (visited.has(currentId)) {
|
|
throw new MountOperationError('现有资产关系已存在循环,请先修复关系', 409)
|
|
}
|
|
visited.add(currentId)
|
|
|
|
const current: { parent_id: number | null } | null = await client.equipment.findUnique({
|
|
where: { id: currentId },
|
|
select: { parent_id: true }
|
|
})
|
|
if (!current) {
|
|
throw new MountOperationError(currentId === parentId ? '父资产不存在' : '父资产关系已变化,请刷新后重试',
|
|
currentId === parentId ? 404 : 409)
|
|
}
|
|
currentId = current.parent_id
|
|
}
|
|
return [...visited]
|
|
}
|
|
|
|
const lockMountAssets = async (
|
|
client: TransactionClient,
|
|
parentId: number,
|
|
children: { id: number; missingMessage: string; missingStatus?: number }[],
|
|
attachingChildId?: number
|
|
) => {
|
|
const ancestors = await loadMountAncestors(client, parentId, attachingChildId)
|
|
const trees = await Promise.all(children.map(async child => {
|
|
try {
|
|
return await loadAssetTree(client, child.id)
|
|
} catch (error) {
|
|
if (error instanceof Error && error.message === '资产不存在') {
|
|
throw new MountOperationError(child.missingMessage, child.missingStatus ?? 404)
|
|
}
|
|
throw error
|
|
}
|
|
}))
|
|
await lockEquipmentRows(client, [...ancestors, ...trees.flatMap(tree => tree.map(item => item.id))])
|
|
const currentAncestors = await loadMountAncestors(client, parentId)
|
|
if (ancestors.join(',') !== currentAncestors.join(',')) {
|
|
throw new MountOperationError('父资产关系已变化,请刷新后重试', 409)
|
|
}
|
|
const currentTrees = await Promise.all(children.map(async child => {
|
|
try {
|
|
return await loadAssetTree(client, child.id)
|
|
} catch (error) {
|
|
if (error instanceof Error && error.message === '资产不存在') {
|
|
throw new MountOperationError('配件已变化,请刷新后重试', 409)
|
|
}
|
|
throw error
|
|
}
|
|
}))
|
|
if (trees.some((tree, index) => getAssetTreeFingerprint(tree) !== getAssetTreeFingerprint(currentTrees[index]))) {
|
|
throw new MountOperationError('配件状态或挂载关系已变化,请刷新后重试', 409)
|
|
}
|
|
return currentTrees
|
|
}
|
|
|
|
const getMountErrorStatus = (error: any) => {
|
|
if (error instanceof MountOperationError) return error.statusCode
|
|
if (Number.isInteger(error?.statusCode)) return error.statusCode
|
|
if (Number.isInteger(error?.status)) return error.status
|
|
if (error?.code === 'P2034' || /deadlock|lock wait timeout/i.test(String(error?.message || ''))) {
|
|
return 409
|
|
}
|
|
return 500
|
|
}
|
|
|
|
export const mountChild = async (req: Request, res: Response) => {
|
|
try {
|
|
const numericParentId = Number(req.params.parentId)
|
|
const { child_id, notes } = req.body as { child_id: number; notes?: string }
|
|
const numericChildId = Number(child_id)
|
|
const userId = Number(res.locals.user?.id)
|
|
|
|
if (!userId) {
|
|
return errorResponse(res, '用户未登录', 401)
|
|
}
|
|
if (!Number.isInteger(numericParentId) || !Number.isInteger(numericChildId) || numericParentId <= 0 || numericChildId <= 0) {
|
|
return errorResponse(res, '资产参数不合法', 422)
|
|
}
|
|
|
|
const updatedParent = await prisma.$transaction(async (tx) => {
|
|
const [childTree] = await lockMountAssets(tx, numericParentId,
|
|
[{ id: numericChildId, missingMessage: '子资产不存在' }], numericChildId)
|
|
const [parent, child] = await Promise.all([
|
|
tx.equipment.findUnique({
|
|
where: { id: numericParentId },
|
|
include: { assetType: true }
|
|
}),
|
|
tx.equipment.findUnique({
|
|
where: { id: numericChildId },
|
|
include: { assetType: true }
|
|
})
|
|
])
|
|
if (!parent) throw new MountOperationError('父资产不存在', 404)
|
|
if (!child) throw new MountOperationError('子资产不存在', 404)
|
|
if (!parent.assetType?.can_be_parent) {
|
|
throw new MountOperationError('该资产类型不支持挂载配件', 400)
|
|
}
|
|
if (!child.assetType?.can_be_child) {
|
|
throw new MountOperationError('该资产类型不能作为配件挂载', 400)
|
|
}
|
|
ensureParentMountOperable(parent, '父资产')
|
|
if (child.parent_id !== null || !['none', 'unmounted'].includes(child.mount_status)) {
|
|
throw new MountOperationError('该配件已被挂载或关系已变化,请刷新后重试', 409)
|
|
}
|
|
await ensureAssetTreeAttachable(tx, childTree, '子资产树')
|
|
await updateAssetTreeState(tx, childTree, {
|
|
rootParentId: numericParentId,
|
|
rootMountStatus: 'mounted',
|
|
targetStatus: resolveMountedChildStatus(parent),
|
|
departmentId: parent.department_id
|
|
})
|
|
|
|
await tx.mountHistory.create({
|
|
data: {
|
|
child_id: numericChildId,
|
|
parent_id: numericParentId,
|
|
operation_type: 'mount',
|
|
operated_by: userId,
|
|
notes
|
|
}
|
|
})
|
|
await refreshParentTotalValueWithChildren(tx, numericParentId)
|
|
|
|
return tx.equipment.findUnique({
|
|
where: { id: numericParentId },
|
|
include: {
|
|
children: {
|
|
select: {
|
|
id: true,
|
|
equipment_code: true,
|
|
equipment_name: true,
|
|
equipment_model: true,
|
|
equipment_type: true,
|
|
unit_price: true,
|
|
status: true
|
|
}
|
|
}
|
|
}
|
|
})
|
|
}, { isolationLevel: Prisma.TransactionIsolationLevel.ReadCommitted })
|
|
|
|
successResponse(res, updatedParent, '挂载成功')
|
|
} catch (error: any) {
|
|
errorResponse(res, error.message || '挂载失败', getMountErrorStatus(error))
|
|
}
|
|
}
|
|
|
|
export const unmountChild = async (req: Request, res: Response) => {
|
|
try {
|
|
const numericParentId = Number(req.params.parentId)
|
|
const { child_id, notes, released_child_status } = req.body as {
|
|
child_id: number
|
|
notes?: string
|
|
released_child_status?: string
|
|
}
|
|
const userId = Number(res.locals.user?.id)
|
|
const detachedChildStatus = resolveDetachedChildStatus(released_child_status)
|
|
const numericChildId = Number(child_id)
|
|
|
|
if (!userId) {
|
|
return errorResponse(res, '用户未登录', 401)
|
|
}
|
|
if (!Number.isInteger(numericParentId) || !Number.isInteger(numericChildId) || numericParentId <= 0 || numericChildId <= 0) {
|
|
return errorResponse(res, '资产参数不合法', 422)
|
|
}
|
|
|
|
await prisma.$transaction(async (tx) => {
|
|
const [childTree] = await lockMountAssets(tx, numericParentId, [{ id: numericChildId, missingMessage: '子资产不存在' }])
|
|
const [parent, child] = await Promise.all([
|
|
tx.equipment.findUnique({ where: { id: numericParentId } }),
|
|
tx.equipment.findUnique({ where: { id: numericChildId } })
|
|
])
|
|
if (!parent) throw new MountOperationError('父资产不存在', 404)
|
|
if (!child) throw new MountOperationError('子资产不存在', 404)
|
|
if (child.parent_id !== numericParentId) {
|
|
throw new MountOperationError('该配件未挂载到此资产或关系已变化', 409)
|
|
}
|
|
ensureParentMountOperable(parent, '父资产')
|
|
await updateAssetTreeState(tx, childTree, {
|
|
rootParentId: null,
|
|
rootMountStatus: 'unmounted',
|
|
targetStatus: detachedChildStatus,
|
|
departmentId: null
|
|
})
|
|
|
|
await tx.mountHistory.create({
|
|
data: {
|
|
child_id: numericChildId,
|
|
parent_id: numericParentId,
|
|
operation_type: 'unmount',
|
|
operated_by: userId,
|
|
notes
|
|
}
|
|
})
|
|
await refreshParentTotalValueWithChildren(tx, numericParentId)
|
|
}, { isolationLevel: Prisma.TransactionIsolationLevel.ReadCommitted })
|
|
|
|
successResponse(res, null, '卸载成功')
|
|
} catch (error: any) {
|
|
errorResponse(res, error.message || '卸载失败', getMountErrorStatus(error))
|
|
}
|
|
}
|
|
|
|
export const replaceChild = async (req: Request, res: Response) => {
|
|
try {
|
|
const numericParentId = Number(req.params.parentId)
|
|
const { old_child_id, new_child_id, notes, released_child_status } = req.body as {
|
|
old_child_id: number
|
|
new_child_id: number
|
|
notes?: string
|
|
released_child_status?: string
|
|
}
|
|
const userId = Number(res.locals.user?.id)
|
|
const detachedChildStatus = resolveDetachedChildStatus(released_child_status)
|
|
const numericOldChildId = Number(old_child_id)
|
|
const numericNewChildId = Number(new_child_id)
|
|
|
|
if (!userId) {
|
|
return errorResponse(res, '用户未登录', 401)
|
|
}
|
|
if (
|
|
!Number.isInteger(numericParentId) || !Number.isInteger(numericOldChildId) ||
|
|
!Number.isInteger(numericNewChildId) || numericParentId <= 0 ||
|
|
numericOldChildId <= 0 || numericNewChildId <= 0
|
|
) {
|
|
return errorResponse(res, '资产参数不合法', 422)
|
|
}
|
|
if (numericOldChildId === numericNewChildId) {
|
|
return errorResponse(res, '旧配件和新配件不能相同', 422)
|
|
}
|
|
|
|
await prisma.$transaction(async (tx) => {
|
|
const [oldChildTree, newChildTree] = await lockMountAssets(tx, numericParentId, [
|
|
{ id: numericOldChildId, missingMessage: '旧配件未挂载到此资产或关系已变化', missingStatus: 409 },
|
|
{ id: numericNewChildId, missingMessage: '新配件不存在' }
|
|
], numericNewChildId)
|
|
const [parent, oldChild, newChild] = await Promise.all([
|
|
tx.equipment.findUnique({
|
|
where: { id: numericParentId },
|
|
include: { assetType: true }
|
|
}),
|
|
tx.equipment.findUnique({ where: { id: numericOldChildId } }),
|
|
tx.equipment.findUnique({
|
|
where: { id: numericNewChildId },
|
|
include: { assetType: true }
|
|
})
|
|
])
|
|
if (!parent) throw new MountOperationError('父资产不存在', 404)
|
|
if (!oldChild || oldChild.parent_id !== numericParentId) {
|
|
throw new MountOperationError('旧配件未挂载到此资产或关系已变化', 409)
|
|
}
|
|
if (!newChild) throw new MountOperationError('新配件不存在', 404)
|
|
if (!parent.assetType?.can_be_parent) {
|
|
throw new MountOperationError('该资产类型不支持挂载配件', 400)
|
|
}
|
|
if (!newChild.assetType?.can_be_child) {
|
|
throw new MountOperationError('新配件类型不能作为配件挂载', 400)
|
|
}
|
|
if (newChild.parent_id !== null || !['none', 'unmounted'].includes(newChild.mount_status)) {
|
|
throw new MountOperationError('新配件已被挂载或关系已变化,请刷新后重试', 409)
|
|
}
|
|
ensureParentMountOperable(parent, '父资产')
|
|
await ensureAssetTreeAttachable(tx, newChildTree, '新配件树')
|
|
await updateAssetTreeState(tx, oldChildTree, {
|
|
rootParentId: null,
|
|
rootMountStatus: 'unmounted',
|
|
targetStatus: detachedChildStatus,
|
|
departmentId: null
|
|
})
|
|
await updateAssetTreeState(tx, newChildTree, {
|
|
rootParentId: numericParentId,
|
|
rootMountStatus: 'mounted',
|
|
targetStatus: resolveMountedChildStatus(parent),
|
|
departmentId: parent.department_id
|
|
})
|
|
|
|
await tx.mountHistory.create({
|
|
data: {
|
|
child_id: numericOldChildId,
|
|
parent_id: numericParentId,
|
|
operation_type: 'replace',
|
|
operated_by: userId,
|
|
notes,
|
|
old_parent_id: numericParentId,
|
|
new_parent_id: null
|
|
}
|
|
})
|
|
|
|
await tx.mountHistory.create({
|
|
data: {
|
|
child_id: numericNewChildId,
|
|
parent_id: numericParentId,
|
|
operation_type: 'replace',
|
|
operated_by: userId,
|
|
notes,
|
|
old_parent_id: null,
|
|
new_parent_id: numericParentId
|
|
}
|
|
})
|
|
await refreshParentTotalValueWithChildren(tx, numericParentId)
|
|
}, { isolationLevel: Prisma.TransactionIsolationLevel.ReadCommitted })
|
|
|
|
successResponse(res, null, '更换成功')
|
|
} catch (error: any) {
|
|
errorResponse(res, error.message || '更换失败', getMountErrorStatus(error))
|
|
}
|
|
}
|
|
|
|
export const getChildren = async (req: Request, res: Response) => {
|
|
try {
|
|
const { parentId } = req.params
|
|
|
|
const parent = await prisma.equipment.findUnique({
|
|
where: { id: Number(parentId) },
|
|
include: {
|
|
children: {
|
|
select: {
|
|
id: true,
|
|
equipment_code: true,
|
|
equipment_name: true,
|
|
equipment_model: true,
|
|
equipment_type: true,
|
|
unit_price: true,
|
|
status: true,
|
|
mount_status: true,
|
|
created_at: true
|
|
}
|
|
}
|
|
}
|
|
})
|
|
|
|
if (!parent) {
|
|
return errorResponse(res, '资产不存在', 404)
|
|
}
|
|
|
|
const totalChildrenValue = calculateChildrenTotalValueFromRecords(parent.children)
|
|
const currentTotalValueWithChildren = calculateCurrentTotalValueWithChildren(
|
|
parent.unit_price,
|
|
parent.children
|
|
)
|
|
|
|
successResponse(
|
|
res,
|
|
{
|
|
children: parent.children,
|
|
total_children_value: totalChildrenValue,
|
|
total_value_with_children: currentTotalValueWithChildren
|
|
},
|
|
'获取成功'
|
|
)
|
|
} catch (error: any) {
|
|
errorResponse(res, error.message || '获取子资产列表失败')
|
|
}
|
|
}
|
|
|
|
export const getMountHistory = async (req: Request, res: Response) => {
|
|
try {
|
|
const { id } = req.params
|
|
|
|
const history = await prisma.mountHistory.findMany({
|
|
where: {
|
|
OR: [
|
|
{ child_id: Number(id) },
|
|
{ parent_id: Number(id) }
|
|
]
|
|
},
|
|
include: {
|
|
child: {
|
|
select: {
|
|
id: true,
|
|
equipment_code: true,
|
|
equipment_name: true
|
|
}
|
|
},
|
|
operator: {
|
|
select: {
|
|
id: true,
|
|
name: true,
|
|
username: true
|
|
}
|
|
}
|
|
},
|
|
orderBy: { operated_at: 'desc' }
|
|
})
|
|
|
|
const historyWithParent = await Promise.all(
|
|
history.map(async (item) => {
|
|
let parentInfo = null
|
|
if (item.parent_id) {
|
|
parentInfo = await prisma.equipment.findUnique({
|
|
where: { id: item.parent_id },
|
|
select: { id: true, equipment_code: true, equipment_name: true }
|
|
})
|
|
}
|
|
return { ...item, parent: parentInfo }
|
|
})
|
|
)
|
|
|
|
successResponse(res, historyWithParent, '获取成功')
|
|
} catch (error: any) {
|
|
errorResponse(res, error.message || '获取挂载历史失败')
|
|
}
|
|
}
|
|
|
|
export const getAvailableChildren = async (req: Request, res: Response) => {
|
|
try {
|
|
const { keyword, equipment_type } = req.query
|
|
|
|
const childTypes = await prisma.assetType.findMany({
|
|
where: { can_be_child: true, status: 'active' },
|
|
select: { name: true }
|
|
})
|
|
const childTypeNames = childTypes.map((item) => item.name)
|
|
|
|
const where: any = {
|
|
parent_id: null,
|
|
mount_status: { in: ['none', 'unmounted'] },
|
|
equipment_type: { in: childTypeNames },
|
|
status: '可用',
|
|
remaining_quantity: { gt: 0 },
|
|
borrow_records: {
|
|
none: {
|
|
status: '已借出'
|
|
}
|
|
}
|
|
}
|
|
|
|
if (keyword) {
|
|
const normalizedKeyword = String(keyword).trim()
|
|
where.OR = [
|
|
{ equipment_name: { contains: normalizedKeyword } },
|
|
{ equipment_code: { contains: normalizedKeyword } },
|
|
{ equipment_model: { contains: normalizedKeyword } },
|
|
{ equipment_type: { contains: normalizedKeyword } }
|
|
]
|
|
}
|
|
|
|
if (equipment_type) {
|
|
where.equipment_type = equipment_type
|
|
}
|
|
|
|
const children = await prisma.equipment.findMany({
|
|
where,
|
|
select: {
|
|
id: true,
|
|
equipment_code: true,
|
|
equipment_name: true,
|
|
equipment_model: true,
|
|
equipment_type: true,
|
|
unit_price: true,
|
|
status: true
|
|
},
|
|
orderBy: { equipment_name: 'asc' },
|
|
take: 50
|
|
})
|
|
|
|
successResponse(res, children, '获取成功')
|
|
} catch (error: any) {
|
|
errorResponse(res, error.message || '获取可挂载配件列表失败')
|
|
}
|
|
}
|