chore: update

This commit is contained in:
2026-03-11 19:57:34 +01:00
parent f6b3948839
commit 375aa38454
62 changed files with 2714 additions and 1981 deletions
+120 -88
View File
@@ -57,7 +57,7 @@ func (d *Database) GetClientByID(id int) (*models.Client, error) {
// GetAllClients récupère tous les clients
func (d *Database) GetAllClients() ([]*models.Client, error) {
query := `SELECT id, username, password, nom, prenom, telephone, command, point, point_zipette, amende, created_at
query := `SELECT id, username, password, nom, prenom, telephone, command, point, point_zipette, amende, referral_balance, created_at
FROM clients ORDER BY created_at DESC`
rows, err := d.Query(query)
@@ -80,6 +80,7 @@ func (d *Database) GetAllClients() ([]*models.Client, error) {
&client.Point,
&client.PointZipette,
&client.Amende,
&client.ReferralBalance,
&client.CreatedAt,
)
if err != nil {
@@ -212,7 +213,7 @@ func (d *Database) GetClientStats(clientID int) (map[string]interface{}, error)
countQuery := `SELECT
COUNT(*) as total,
SUM(CASE WHEN status = 'pending' OR status = 'support' OR status = 'livre' THEN 1 ELSE 0 END) as pending,
SUM(CASE WHEN status = 'pending' OR status = 'livre' THEN 1 ELSE 0 END) as pending,
SUM(CASE WHEN status = 'approved' THEN 1 ELSE 0 END) as completed
FROM commandes WHERE username = $1`
@@ -856,128 +857,159 @@ func (d *Database) CalculateAndAddPointsForCommand(commandID int, username strin
return totalPoints, nil
}
func (d *Database) CalculateAndAddPointsForCommandTx(tx *sql.Tx, commandID int, username string) (int, error) {
func (d *Database) CalculateAndAddPointsForCommandTx(tx *sql.Tx, commandID int, username string) (int, string, error) {
log.Printf("💰 [CalcPointsTx] START - cmd=%d, user=%s", commandID, username)
// Charger les paramètres globaux
settings, err := d.GetSettings()
if err != nil {
log.Printf("⚠️ [CalcPointsTx] Erreur lecture settings, utilisation des défauts: %v", err)
settings = DefaultSettings()
}
// Construire les sets de catégories par pool
weedCats := make(map[string]bool)
for _, cat := range settings.PointsCategoriesWeed {
weedCats[strings.ToLower(cat)] = true
}
zipetteCats := make(map[string]bool)
for _, cat := range settings.PointsCategoriesZipette {
zipetteCats[strings.ToLower(cat)] = true
}
// pool "total" → toujours compté dans le pool weed (point)
totalCats := make(map[string]bool)
for _, cat := range settings.PointsCategoriesTotal {
totalCats[strings.ToLower(cat)] = true
}
// Si aucune catégorie configurée → pas de points
if !settings.PointsSeparated {
// Mode non-séparé : seul le pool Total est actif
if len(weedCats) == 0 && len(zipetteCats) == 0 && len(totalCats) == 0 {
log.Printf("️ [CalcPointsTx] Mode non-séparé : aucune catégorie configurée → 0 points")
return 0, "", nil
}
} else {
// Mode séparé : seuls W et Z sont actifs (T ignoré)
if len(weedCats) == 0 && len(zipetteCats) == 0 {
log.Printf("️ [CalcPointsTx] Mode séparé : aucune catégorie W/Z configurée → 0 points")
return 0, "", nil
}
}
// ✅ ÉTAPE 1: Récupérer tous les items de la commande avec leurs catégories
query := `
SELECT ci.quantite, ci.prix, COALESCE(p.category, 'weed_hash') as category
rows, err := tx.Query(`
SELECT ci.quantite, ci.prix, COALESCE(p.category, '') as category
FROM command_items ci
LEFT JOIN products p ON ci.product_id = p.id
WHERE ci.command_id = $1
`
rows, err := tx.Query(query, commandID)
`, commandID)
if err != nil {
log.Printf("❌ [CalcPointsTx] Erreur query items: %v", err)
return 0, fmt.Errorf("erreur récupération items: %w", err)
return 0, "", fmt.Errorf("erreur récupération items: %w", err)
}
defer rows.Close()
type ItemPoints struct {
Category string
Quantite float64
Prix float64
}
var items []ItemPoints
totalPrixWeedHash := 0.0
var itemCount int
totalPrixWeed := 0.0
totalPrixZipette := 0.0
totalPrixTotal := 0.0
for rows.Next() {
var item ItemPoints
if err := rows.Scan(&item.Quantite, &item.Prix, &item.Category); err != nil {
var quantite, prix float64
var category string
if err := rows.Scan(&quantite, &prix, &category); err != nil {
log.Printf("❌ [CalcPointsTx] Erreur scan: %v", err)
return 0, fmt.Errorf("erreur lecture item: %w", err)
return 0, "", fmt.Errorf("erreur lecture item: %w", err)
}
items = append(items, item)
// Cumuler par catégorie
categoryLower := strings.ToLower(item.Category)
if categoryLower == "zipette&co" || categoryLower == "zipette_co" {
totalPrixZipette += item.Prix
} else if categoryLower == "gros&semi" || categoryLower == "gros_semi" {
// gros&semi → 0 points, on ne cumule pas
} else {
// weed_hash ou autres catégories
totalPrixWeedHash += item.Prix
itemCount++
catLower := strings.ToLower(category)
if weedCats[catLower] {
totalPrixWeed += prix
} else if zipetteCats[catLower] {
totalPrixZipette += prix
} else if totalCats[catLower] {
totalPrixTotal += prix
}
}
if err = rows.Err(); err != nil {
log.Printf("❌ [CalcPointsTx] Erreur rows: %v", err)
return 0, fmt.Errorf("erreur itération items: %w", err)
return 0, "", fmt.Errorf("erreur itération items: %w", err)
}
if len(items) == 0 {
if itemCount == 0 {
log.Printf("⚠️ [CalcPointsTx] Aucun item trouvé pour cmd %d", commandID)
return 0, nil
return 0, "", nil
}
log.Printf("📊 [CalcPointsTx] %d items - weed_hash: %.2f€, zipette: %.2f€",
len(items), totalPrixWeedHash, totalPrixZipette)
log.Printf("📊 [CalcPointsTx] %d items - weed: %.2f€, zipette: %.2f€, total: %.2f€",
itemCount, totalPrixWeed, totalPrixZipette, totalPrixTotal)
// ✅ ÉTAPE 2: Calculer les points par catégorie avec le bon barème
pointsWeedHash := 0
switch {
case totalPrixWeedHash >= 30 && totalPrixWeedHash <= 50:
pointsWeedHash = 1
case totalPrixWeedHash >= 60 && totalPrixWeedHash <= 150:
pointsWeedHash = 2
case totalPrixWeedHash >= 160 && totalPrixWeedHash <= 300:
pointsWeedHash = 3
case totalPrixWeedHash >= 310 && totalPrixWeedHash <= 400:
pointsWeedHash = 5
case totalPrixWeedHash >= 400:
pointsWeedHash = 10
}
// ✅ ÉTAPE 2: Calculer les points
var totalPoints int
var pointCategory string
var result sql.Result
pointsZipette := 0
switch {
case totalPrixZipette >= 30 && totalPrixZipette <= 100:
pointsZipette = 1
case totalPrixZipette >= 110 && totalPrixZipette <= 200:
pointsZipette = 2
case totalPrixZipette >= 210:
pointsZipette = 3
}
if !settings.PointsSeparated {
// ── Mode non-séparé : Barème Total appliqué sur W + Z + T ──────────────
allTotal := totalPrixWeed + totalPrixZipette + totalPrixTotal
totalPoints = CalcPointsFromTiers(allTotal, settings.PointsTotalTiers)
pointCategory = "total"
totalPoints := pointsWeedHash + pointsZipette
log.Printf("💰 [CalcPointsTx] Mode non-séparé - total: %.2f€ → %d pts (barème Total)",
allTotal, totalPoints)
log.Printf("💰 [CalcPointsTx] Points calculés - weed_hash: %d, zipette: %d, total: %d",
pointsWeedHash, pointsZipette, totalPoints)
if totalPoints == 0 {
return 0, "", nil
}
// ✅ ÉTAPE 3: Mettre à jour les points du client (dans la transaction)
if pointsWeedHash > 0 || pointsZipette > 0 {
updateQuery := `
result, err = tx.Exec(`
UPDATE clients
SET
point = point + $1,
point_zipette = point_zipette + $2,
updated_at = CURRENT_TIMESTAMP
SET point = point + $1, updated_at = CURRENT_TIMESTAMP
WHERE username = $2
`, totalPoints, username)
} else {
// ── Mode séparé : Barèmes W et Z, pool T ignoré ────────────────────────
pointsWeed := CalcPointsFromTiers(totalPrixWeed, settings.PointsWeedTiers)
pointsZipette := CalcPointsFromTiers(totalPrixZipette, settings.PointsZipetteTiers)
totalPoints = pointsWeed + pointsZipette
log.Printf("💰 [CalcPointsTx] Mode séparé - weed: %d pts, zipette: %d pts",
pointsWeed, pointsZipette)
if totalPoints == 0 {
return 0, "", nil
}
if pointsWeed > 0 && pointsZipette > 0 {
pointCategory = "mixed"
} else if pointsZipette > 0 {
pointCategory = "zipette&co"
} else {
pointCategory = "weed&hash"
}
result, err = tx.Exec(`
UPDATE clients
SET point = point + $1, point_zipette = point_zipette + $2, updated_at = CURRENT_TIMESTAMP
WHERE username = $3
`
result, err := tx.Exec(updateQuery, pointsWeedHash, pointsZipette, username)
if err != nil {
log.Printf("❌ [CalcPointsTx] Erreur UPDATE points: %v", err)
return 0, fmt.Errorf("erreur mise à jour points: %w", err)
}
rows, _ := result.RowsAffected()
if rows == 0 {
log.Printf("⚠️ [CalcPointsTx] Client %s non trouvé", username)
return 0, fmt.Errorf("client non trouvé")
}
log.Printf("✅ [CalcPointsTx] Points ajoutés: +%d weed_hash, +%d zipette pour %s",
pointsWeedHash, pointsZipette, username)
`, pointsWeed, pointsZipette, username)
}
log.Printf("🎉 [CalcPointsTx] SUCCÈS - Total %d points attribués", totalPoints)
if err != nil {
log.Printf("❌ [CalcPointsTx] Erreur UPDATE points: %v", err)
return 0, "", fmt.Errorf("erreur mise à jour points: %w", err)
}
affected, _ := result.RowsAffected()
if affected == 0 {
log.Printf("⚠️ [CalcPointsTx] Client %s non trouvé", username)
return 0, "", fmt.Errorf("client non trouvé")
}
return totalPoints, nil
log.Printf("🎉 [CalcPointsTx] SUCCÈS - %d points [%s] → %s", totalPoints, pointCategory, username)
return totalPoints, pointCategory, nil
}
func (d *Database) CanUserAccessCommand(