增加删除原料校验
This commit is contained in:
@@ -24,6 +24,7 @@ var (
|
||||
ErrRawMaterialNameConflict = fmt.Errorf("原料名称已存在")
|
||||
ErrRawMaterialNotFound = fmt.Errorf("原料不存在")
|
||||
ErrStockNotEmpty = fmt.Errorf("原料尚有库存,无法删除")
|
||||
ErrRawMaterialInUseByRecipe = fmt.Errorf("原料已被配方使用,无法删除")
|
||||
)
|
||||
|
||||
// RawMaterialService 定义了原料领域的核心业务服务接口
|
||||
@@ -138,6 +139,15 @@ func (s *rawMaterialServiceImpl) DeleteRawMaterial(ctx context.Context, id uint3
|
||||
return ErrStockNotEmpty
|
||||
}
|
||||
|
||||
// 检查原料是否被配方使用
|
||||
isUsed, err := s.rawMaterialRepo.IsRawMaterialUsedInRecipes(serviceCtx, id)
|
||||
if err != nil {
|
||||
return fmt.Errorf("检查原料是否被配方使用失败: %w", err)
|
||||
}
|
||||
if isUsed {
|
||||
return ErrRawMaterialInUseByRecipe
|
||||
}
|
||||
|
||||
if err := s.rawMaterialRepo.DeleteRawMaterial(serviceCtx, id); err != nil {
|
||||
return fmt.Errorf("删除原料失败: %w", err)
|
||||
}
|
||||
|
||||
@@ -41,6 +41,7 @@ type RawMaterialRepository interface {
|
||||
DeleteRawMaterial(ctx context.Context, id uint32) error
|
||||
DeleteNutrientsByRawMaterialIDTx(ctx context.Context, db *gorm.DB, rawMaterialID uint32) error
|
||||
CreateBatchRawMaterialNutrientsTx(ctx context.Context, db *gorm.DB, nutrients []models.RawMaterialNutrient) error
|
||||
IsRawMaterialUsedInRecipes(ctx context.Context, rawMaterialID uint32) (bool, error)
|
||||
|
||||
// 库存日志相关方法
|
||||
CreateRawMaterialStockLog(ctx context.Context, log *models.RawMaterialStockLog) error
|
||||
@@ -329,3 +330,16 @@ func (r *gormRawMaterialRepository) ListStockLogs(ctx context.Context, opts Stoc
|
||||
|
||||
return logs, total, nil
|
||||
}
|
||||
|
||||
// IsRawMaterialUsedInRecipes 检查原料是否被任何配方使用
|
||||
func (r *gormRawMaterialRepository) IsRawMaterialUsedInRecipes(ctx context.Context, rawMaterialID uint32) (bool, error) {
|
||||
repoCtx := logs.AddFuncName(ctx, r.ctx, "IsRawMaterialUsedInRecipes")
|
||||
var count int64
|
||||
err := r.db.WithContext(repoCtx).Model(&models.RecipeIngredient{}).
|
||||
Where("raw_material_id = ?", rawMaterialID).
|
||||
Count(&count).Error
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("查询原料是否被配方使用失败: %w", err)
|
||||
}
|
||||
return count > 0, nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user