fix: support safe project deletion
This commit is contained in:
@@ -132,6 +132,50 @@ func (s *Server) updateProject(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusOK, map[string]any{"project": projectView(project)})
|
||||
}
|
||||
|
||||
func (s *Server) deleteProject(w http.ResponseWriter, r *http.Request) {
|
||||
projectID := r.PathValue("id")
|
||||
if err := validateUUID(projectID); err != nil {
|
||||
writeError(w, err)
|
||||
return
|
||||
}
|
||||
|
||||
err := s.db.WithContext(r.Context()).Transaction(func(tx *gorm.DB) error {
|
||||
var project model.Project
|
||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&project, "id = ?", projectID).Error; err != nil {
|
||||
return mapNotFound(err, "PROJECT_NOT_FOUND", "项目不存在")
|
||||
}
|
||||
|
||||
var historyCount int64
|
||||
if err := tx.Model(&model.QueueSession{}).Where("project_id = ?", projectID).Count(&historyCount).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if historyCount > 0 {
|
||||
return &apiError{
|
||||
Status: http.StatusConflict,
|
||||
Code: "PROJECT_HAS_HISTORY",
|
||||
Message: "该项目已有排队运营历史,不能删除;如需停止使用,请结束该项目。",
|
||||
}
|
||||
}
|
||||
|
||||
if err := tx.Model(&model.AuditEntry{}).
|
||||
Where("project_id = ?", projectID).
|
||||
Update("project_id", nil).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
actor := currentPrincipal(r.Context()).User
|
||||
if err := s.addAudit(tx, r, nil, &actor.ID, "PROJECT_DELETED", "PROJECT", &projectID,
|
||||
map[string]any{"project": projectView(project)}); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Delete(&project).Error
|
||||
})
|
||||
if err != nil {
|
||||
writeError(w, err)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
type adminUserRequest struct {
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
|
||||
Reference in New Issue
Block a user