// ============================================ // db/cancel_sanctions_db.go // GESTION DES SANCTIONS ÉVOLUTIVES // ============================================ package db import ( "fmt" "gestion/models" "log" "sort" "gorm.io/gorm" ) // GetClientCancellationsCount récupère le nombre d'annulations tardives d'un client func (d *Database) GetClientCancellationsCount(username string) (int, error) { var result struct { Count int `gorm:"column:count"` } err := d.GDB.Table("clients").Select("COALESCE(cancellations_count, 0) as count").Where("username = ?", username).Scan(&result).Error if err != nil { log.Printf("❌ [GetCancellationsCount] Erreur: %v", err) return 0, fmt.Errorf("erreur récupération compteur: %w", err) } return result.Count, nil } // IncrementClientCancellationsCount incrémente le compteur d'annulations func (d *Database) IncrementClientCancellationsCount(username string) error { result := d.GDB.Model(&models.Client{}).Where("username = ?", username).Updates(map[string]any{ "cancellations_count": gorm.Expr("COALESCE(cancellations_count, 0) + 1"), }) if result.Error != nil { log.Printf("❌ [IncrementCancellations] Erreur: %v", result.Error) return fmt.Errorf("erreur incrémentation: %w", result.Error) } if result.RowsAffected == 0 { return fmt.Errorf("client non trouvé") } cacheKey := fmt.Sprintf("client:%s", username) Redis.Del(RedisCtx, cacheKey) return nil } // penaltyForCount retourne le montant du palier applicable pour un nombre d'annulations donné func penaltyForCount(count int, tiers []models.PenaltyTier) int { if len(tiers) == 0 { return 0 } sorted := make([]models.PenaltyTier, len(tiers)) copy(sorted, tiers) sort.Slice(sorted, func(i, j int) bool { return sorted[i].MinCancel > sorted[j].MinCancel }) for _, t := range sorted { if count >= t.MinCancel { return t.Amount } } return sorted[len(sorted)-1].Amount } // CalculateCancellationPenalty calcule la pénalité selon l'historique et le barème configuré func (d *Database) CalculateCancellationPenalty(username string) (int, error) { count, err := d.GetClientCancellationsCount(username) if err != nil { return 0, err } settings, err := d.GetSettings() if err != nil { log.Printf("⚠️ [CalculatePenalty] Impossible de charger les settings, barème par défaut: %v", err) settings = DefaultSettings() } penalty := penaltyForCount(count, settings.PenaltyTiers) log.Printf("💰 [CalculatePenalty] Client %s - Annulations: %d → Pénalité: %d points", username, count, penalty) return penalty, nil } // ApplyCancellationPenalty applique une pénalité et incrémente le compteur d'annulations func (d *Database) ApplyCancellationPenalty(username string) (int, error) { penalty, err := d.CalculateCancellationPenalty(username) if err != nil { return 0, err } log.Printf("⚠️ [ApplyCancellationPenalty] Client %s - Pénalité calculée: %d points", username, penalty) if err := d.IncrementClientCancellationsCount(username); err != nil { return 0, err } result := d.GDB.Model(&models.Client{}).Where("username = ?", username).Update("amende", float64(penalty)) if result.Error != nil { log.Printf("❌ [ApplyCancellationPenalty] Erreur UPDATE: %v", result.Error) return 0, fmt.Errorf("erreur application pénalité: %w", result.Error) } if result.RowsAffected == 0 { return 0, fmt.Errorf("client non trouvé") } log.Printf("✅ [ApplyCancellationPenalty] Amende %d appliquée à %s", penalty, username) cacheKey := fmt.Sprintf("client:%s", username) Redis.Del(RedisCtx, cacheKey) return penalty, nil } // GetClientCancellationHistory récupère l'historique d'annulations d'un client func (d *Database) GetClientCancellationHistory(username string) (map[string]any, error) { nextPenalty, err := d.CalculateCancellationPenalty(username) if err != nil { return nil, err } count, err := d.GetClientCancellationsCount(username) if err != nil { return nil, err } settings, _ := d.GetSettings() client, err := d.GetClientByUsername(username) var currentAmende float64 if err == nil { currentAmende = client.Amende } return map[string]any{ "cancellations_count": count, "current_amende": currentAmende, "next_penalty": nextPenalty, "penalty_tiers": settings.PenaltyTiers, "warning": "Une amende sera appliquée lors de la prochaine annulation tardive", }, nil }