删除设备模板时检查和删除区域主控时检查

This commit is contained in:
2025-11-03 17:11:51 +08:00
parent f569876225
commit f0b71b47a0
7 changed files with 274 additions and 43 deletions

View File

@@ -47,26 +47,11 @@ func (r *gormAreaControllerRepository) Update(ac *models.AreaController) error {
}
// Delete 删除一个 AreaController 记录。
// 在删除前会检查是否有设备关联到该主控,如果有,则不允许删除。
func (r *gormAreaControllerRepository) Delete(id uint) error {
return r.db.Transaction(func(tx *gorm.DB) error {
// 检查是否有设备关联到这个区域主控
var count int64
if err := tx.Model(&models.Device{}).Where("area_controller_id = ?", id).Count(&count).Error; err != nil {
return fmt.Errorf("检查关联设备失败: %w", err)
}
if count > 0 {
return fmt.Errorf("无法删除区域主控,因为仍有 %d 个设备关联到它", count)
}
// 如果没有关联设备,则执行删除操作
if err := tx.Delete(&models.AreaController{}, id).Error; err != nil {
return fmt.Errorf("删除区域主控失败: %w", err)
}
return nil
})
if err := r.db.Delete(&models.AreaController{}, id).Error; err != nil {
return fmt.Errorf("删除区域主控失败: %w", err)
}
return nil
}
// FindByID 通过 ID 查找一个 AreaController。

View File

@@ -46,6 +46,9 @@ type DeviceRepository interface {
// IsDeviceInUse 检查设备是否被任何任务使用
IsDeviceInUse(deviceID uint) (bool, error)
// IsAreaControllerInUse 检查区域主控是否被任何设备使用
IsAreaControllerInUse(areaControllerID uint) (bool, error)
}
// gormDeviceRepository 是 DeviceRepository 的 GORM 实现
@@ -175,3 +178,12 @@ func (r *gormDeviceRepository) IsDeviceInUse(deviceID uint) (bool, error) {
}
return count > 0, nil
}
// IsAreaControllerInUse 检查区域主控是否被任何设备使用
func (r *gormDeviceRepository) IsAreaControllerInUse(areaControllerID uint) (bool, error) {
var count int64
if err := r.db.Model(&models.Device{}).Where("area_controller_id = ?", areaControllerID).Count(&count).Error; err != nil {
return false, fmt.Errorf("检查区域主控使用情况失败: %w", err)
}
return count > 0, nil
}

View File

@@ -83,12 +83,8 @@ func (r *gormDeviceTemplateRepository) IsInUse(id uint) (bool, error) {
// Delete 软删除数据库中的设备模板
func (r *gormDeviceTemplateRepository) Delete(id uint) error {
inUse, err := r.IsInUse(id)
if err != nil {
return err
if err := r.db.Delete(&models.DeviceTemplate{}, id).Error; err != nil {
return fmt.Errorf("删除设备模板失败: %w", err)
}
if inUse {
return errors.New("设备模板正在被设备使用,无法删除")
}
return r.db.Delete(&models.DeviceTemplate{}, id).Error
return nil
}