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
+3 -3
View File
@@ -11,7 +11,7 @@ func AddAddress(c *gin.Context) {
database := c.MustGet("database").(*db.Database)
userRole := c.GetString("role")
if userRole != "admin" {
if userRole != "admin" && userRole != "cabine" {
c.JSON(http.StatusForbidden, gin.H{"error": "Accès réservé aux administrateurs"})
return
}
@@ -37,7 +37,7 @@ func DeleteAddress(c *gin.Context) {
database := c.MustGet("database").(*db.Database)
userRole := c.GetString("role")
if userRole != "admin" {
if userRole != "admin" && userRole != "cabine" {
c.JSON(http.StatusForbidden, gin.H{"error": "Accès réservé aux administrateurs"})
return
}
@@ -61,7 +61,7 @@ func DeleteAddress(c *gin.Context) {
func GetAllAddress(c *gin.Context) {
database := c.MustGet("database").(*db.Database)
userRole := c.GetString("role")
if userRole != "admin" {
if userRole != "admin" && userRole != "cabine" {
c.JSON(http.StatusForbidden, gin.H{"error": "Accès réservé aux administrateurs"})
return
}
+8 -1
View File
@@ -22,8 +22,15 @@ func AlertPolice(c *gin.Context) {
c.JSON(http.StatusForbidden, gin.H{"error": "Accès réservé aux livreurs"})
return
}
var req struct {
Message string `json:"message"`
}
// message optionnel — on ignore l'erreur de bind
_ = c.ShouldBindJSON(&req)
usernameStr := username.(string)
alert, err := database.CreateAlert(usernameStr)
alert, err := database.CreateAlert(usernameStr, req.Message)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
+1
View File
@@ -738,6 +738,7 @@ func GetAllClients(c *gin.Context) {
"amende": cl.Amende,
"cancellations_count": cl.CancellationsCount,
"last_penalty_reason": cl.LastPenaltyReason,
"referral_balance": cl.ReferralBalance,
})
}
+3 -3
View File
@@ -528,8 +528,8 @@ func AddDeliverySupport(c *gin.Context) {
err = database.AddCommandLog(
commandID,
"support",
fmt.Sprintf("Support cabine: %s", req.Message),
"note",
fmt.Sprintf("Note cabine: %s", req.Message),
cabineUsername.(string),
)
@@ -630,7 +630,7 @@ func ForceValidateDelivery(c *gin.Context) {
return
}
validStatuses := []string{"assigned", "in_transit", "en_route", "en_cours", "support", "pending", "priority"}
validStatuses := []string{"assigned", "in_transit", "en_route", "en_cours", "pending", "priority"}
isValidStatus := false
for _, vs := range validStatuses {
if status == vs {
+136
View File
@@ -0,0 +1,136 @@
package handlers
import (
"gestion/db"
"log"
"net/http"
"strconv"
"strings"
"github.com/gin-gonic/gin"
)
// GET /api/v1/categories — public
func GetCategories(c *gin.Context) {
database := c.MustGet("database").(*db.Database)
categories, err := database.GetAllCategories()
if err != nil {
log.Printf("❌ [CATEGORIES] Erreur: %v", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "Erreur récupération catégories"})
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"categories": categories,
})
}
// POST /api/v2/admin/protected/categories — admin
func CreateCategory(c *gin.Context) {
database := c.MustGet("database").(*db.Database)
var req struct {
Name string `json:"name" binding:"required"`
Color string `json:"color"`
IsComingSoon bool `json:"is_coming_soon"`
}
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Nom de catégorie requis"})
return
}
name := strings.ToLower(strings.TrimSpace(req.Name))
if len(name) < 2 || len(name) > 100 {
c.JSON(http.StatusBadRequest, gin.H{"error": "Le nom doit faire entre 2 et 100 caractères"})
return
}
if err := db.ValidateCategoryColor(req.Color); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
category, err := database.CreateCategory(name, req.Color, req.IsComingSoon)
if err != nil {
log.Printf("❌ [CATEGORIES] Création erreur: %v", err)
c.JSON(http.StatusConflict, gin.H{"error": "Cette catégorie existe déjà"})
return
}
log.Printf("✅ [CATEGORIES] Créée: %s (couleur: %s)", name, category.Color)
c.JSON(http.StatusCreated, gin.H{
"success": true,
"category": category,
})
}
// PUT /api/v2/admin/protected/categories/:id — admin
func UpdateCategory(c *gin.Context) {
database := c.MustGet("database").(*db.Database)
id, err := strconv.Atoi(c.Param("id"))
if err != nil || id <= 0 {
c.JSON(http.StatusBadRequest, gin.H{"error": "ID invalide"})
return
}
var req struct {
Name string `json:"name" binding:"required"`
Color string `json:"color"`
IsComingSoon bool `json:"is_coming_soon"`
}
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Nom de catégorie requis"})
return
}
name := strings.ToLower(strings.TrimSpace(req.Name))
if len(name) < 2 || len(name) > 100 {
c.JSON(http.StatusBadRequest, gin.H{"error": "Le nom doit faire entre 2 et 100 caractères"})
return
}
if err := db.ValidateCategoryColor(req.Color); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
category, err := database.UpdateCategory(id, name, req.Color, req.IsComingSoon)
if err != nil {
log.Printf("❌ [CATEGORIES] Mise à jour erreur: %v", err)
c.JSON(http.StatusConflict, gin.H{"error": "Ce nom existe déjà ou catégorie introuvable"})
return
}
log.Printf("✅ [CATEGORIES] Mise à jour: %d → %s (couleur: %s)", id, name, category.Color)
c.JSON(http.StatusOK, gin.H{
"success": true,
"category": category,
})
}
// DELETE /api/v2/admin/protected/categories/:id — admin
func DeleteCategory(c *gin.Context) {
database := c.MustGet("database").(*db.Database)
id, err := strconv.Atoi(c.Param("id"))
if err != nil || id <= 0 {
c.JSON(http.StatusBadRequest, gin.H{"error": "ID invalide"})
return
}
if err := database.DeleteCategory(id); err != nil {
log.Printf("❌ [CATEGORIES] Suppression erreur: %v", err)
if strings.Contains(err.Error(), "utilisée par") {
c.JSON(http.StatusConflict, gin.H{"error": err.Error()})
} else {
c.JSON(http.StatusNotFound, gin.H{"error": "Catégorie non trouvée"})
}
return
}
log.Printf("✅ [CATEGORIES] Supprimée: %d", id)
c.JSON(http.StatusOK, gin.H{"success": true, "message": "Catégorie supprimée"})
}
@@ -1,8 +1,3 @@
// ============================================
// handlers/client_tracking.go - NOUVEAU FICHIER
// SUIVI COMMANDE POUR CLIENTS
// ============================================
package handlers
import (
@@ -208,7 +203,6 @@ func getStatusMessage(status string) string {
messages := map[string]string{
"pending": "⏳ En attente d'assignation",
"assigned": "✅ Livreur assigné",
"support": "👨‍💼 En préparation",
"en_route": "🚗 En cours de livraison",
"arrived": "📍 Livreur arrivé",
"livre": "📦 Livré - En attente de confirmation",
@@ -250,7 +244,6 @@ func getStatusIcon(status string) string {
icons := map[string]string{
"created": "🛒",
"assigned": "👤",
"support": "📦",
"en_route": "🚗",
"arrived": "📍",
"livre": "✅",
+24 -352
View File
@@ -1,8 +1,3 @@
// ============================================
// handlers/commands_handlers_CORRIGES.go
// ============================================
// ⚠️ CreateCommandFromBasket SUPPRIMÉ (utiliser ValidateBasket à la place)
package handlers
import (
@@ -12,6 +7,7 @@ import (
"net/http"
"strconv"
"strings"
"sync"
"time"
"github.com/gin-gonic/gin"
@@ -19,14 +15,17 @@ import (
var (
rateLimitMap = make(map[string][]time.Time)
rateLimitMu sync.Mutex
maxRequests = 10
timeWindow = time.Minute
)
func checkRateLimit(key string) bool {
rateLimitMu.Lock()
defer rateLimitMu.Unlock()
now := time.Now()
if timestamps, exists := rateLimitMap[key]; exists {
// Nettoyer les anciennes entrées
var validTimestamps []time.Time
for _, ts := range timestamps {
if now.Sub(ts) < timeWindow {
@@ -399,7 +398,7 @@ func ApproveDelivery(c *gin.Context) {
// ✅ TRANSACTION ATOMIQUE dans la DB pour éviter race condition
// Cette fonction doit être créée dans le fichier db
totalPoints, err := database.ApproveDeliveryAtomic(commandID, username)
totalPoints, pointCategory, err := database.ApproveDeliveryAtomic(commandID, username)
if err != nil {
log.Printf("❌ [APPROVE] Erreur: %v", err)
// ❌ Ne pas exposer les détails de l'erreur
@@ -409,13 +408,14 @@ func ApproveDelivery(c *gin.Context) {
return
}
log.Printf("✅ [APPROVE] %d points attribués à %s", totalPoints, username)
log.Printf("✅ [APPROVE] %d points attribués à %s (catégorie: %s)", totalPoints, username, pointCategory)
c.JSON(http.StatusOK, gin.H{
"success": true,
"message": "Livraison confirmée",
"command_id": commandID,
"points_earned": totalPoints,
"category": pointCategory,
})
}
@@ -446,14 +446,14 @@ func StaffApproveDelivery(c *gin.Context) {
log.Printf("✅ [STAFF_APPROVE] %s (%s) confirme réception cmd %d", staffUsername, role, commandID)
totalPoints, clientUsername, err := database.ApproveDeliveryAtomicByStaff(commandID, staffUsername)
totalPoints, pointCategory, clientUsername, err := database.ApproveDeliveryAtomicByStaff(commandID, staffUsername)
if err != nil {
log.Printf("❌ [STAFF_APPROVE] Erreur: %v", err)
c.JSON(http.StatusBadRequest, gin.H{"error": "Impossible de confirmer la réception: " + err.Error()})
return
}
log.Printf("✅ [STAFF_APPROVE] %d points attribués au client %s", totalPoints, clientUsername)
log.Printf("✅ [STAFF_APPROVE] %d points attribués au client %s (catégorie: %s)", totalPoints, clientUsername, pointCategory)
c.JSON(http.StatusOK, gin.H{
"success": true,
@@ -461,6 +461,7 @@ func StaffApproveDelivery(c *gin.Context) {
"command_id": commandID,
"client_username": clientUsername,
"points_earned": totalPoints,
"category": pointCategory,
})
}
@@ -542,7 +543,7 @@ func ValidateDelivery(c *gin.Context) {
currentStatus, _ := command["status"].(string)
validStatuses := []string{"assigned", "en_route", "pending", "support", "livre"}
validStatuses := []string{"assigned", "en_route", "pending", "livre"}
isValid := false
for _, s := range validStatuses {
if currentStatus == s {
@@ -674,7 +675,7 @@ func AssignDeliveryPerson(c *gin.Context) {
return
}
database.AddCommandLog(commandID, "support",
database.AddCommandLog(commandID, "assigned",
fmt.Sprintf("Livreur '%s' assigné manuellement par %s", livreurUsername, staffUsername),
staffUsername.(string))
@@ -689,131 +690,6 @@ func AssignDeliveryPerson(c *gin.Context) {
})
}
// DisableCommands désactive une ou plusieurs commandes
// POST /api/v1/admin/commands/disable
func DisableCommands(c *gin.Context) {
database := c.MustGet("database").(*db.Database)
var req struct {
CommandIDs []int `json:"command_ids" binding:"required"`
Reason string `json:"reason"`
}
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": "Données invalides",
"details": err.Error(),
})
return
}
if len(req.CommandIDs) == 0 {
c.JSON(http.StatusBadRequest, gin.H{
"error": "Aucun ID de commande fourni",
})
return
}
adminUsername, exists := c.Get("username")
if !exists {
adminUsername = "admin"
}
log.Printf("❌ [DISABLE] Désactivation de %d commande(s) par %s", len(req.CommandIDs), adminUsername)
disabledCount := 0
failedCount := 0
errors := []string{}
for _, commandID := range req.CommandIDs {
command, err := database.GetCommandByID(commandID)
if err != nil {
errors = append(errors, "Commande "+strconv.Itoa(commandID)+" non trouvée")
failedCount++
continue
}
currentStatus := command["status"].(string)
if currentStatus == "disabled" {
errors = append(errors, "Commande "+strconv.Itoa(commandID)+" déjà désactivée")
failedCount++
continue
}
err = database.UpdateCommandStatus(commandID, "disabled")
if err != nil {
errors = append(errors, "Erreur désactivation cmd "+strconv.Itoa(commandID))
failedCount++
continue
}
reason := req.Reason
if reason == "" {
reason = "Désactivée par admin"
}
database.AddCommandLog(commandID, "disabled", reason, adminUsername.(string))
disabledCount++
log.Printf("✅ [DISABLE] Commande %d désactivée", commandID)
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"message": "Traitement des commandes terminé",
"disabled_count": disabledCount,
"failed_count": failedCount,
"errors": errors,
})
}
// ============================================
// COMMANDES CLIENT (My Orders)
// ============================================
// GetMyCommands récupère les commandes du client authentifié
// GET /api/v1/my-commands?status=pending
func GetMyCommands(c *gin.Context) {
database := c.MustGet("database").(*db.Database)
// ✅ SÉCURITÉ: Récupérer depuis JWT validé
username, exists := c.Get("username")
if !exists {
log.Printf("❌ [MY_CMDS] Utilisateur non authentifié")
c.JSON(http.StatusUnauthorized, gin.H{
"error": "Utilisateur non authentifié",
})
return
}
usernameStr := username.(string)
status := c.Query("status")
// ✅ NOUVEAU: Paramètre pour exclure les commandes approved
excludeApproved := c.Query("exclude_approved") == "true"
log.Printf("📋 [MY_CMDS] Récupération pour %s (status=%s, exclude_approved=%v)",
usernameStr, status, excludeApproved)
// ✅ Utiliser la nouvelle fonction avec filtrage
commands, err := database.GetCommandsWithFilter(status, usernameStr, excludeApproved)
if err != nil {
log.Printf("❌ [MY_CMDS] Erreur: %v", err)
c.JSON(http.StatusInternalServerError, gin.H{
"error": "Erreur lors de la récupération des commandes",
"details": err.Error(),
})
return
}
log.Printf("✅ [MY_CMDS] Trouvées: %d commandes", len(commands))
c.JSON(http.StatusOK, gin.H{
"success": true,
"commands": commands,
"count": len(commands),
})
}
func GetClientCommandsHistory(c *gin.Context) {
database := c.MustGet("database").(*db.Database)
@@ -924,9 +800,9 @@ func NotifyClientToDescend(c *gin.Context) {
log.Printf("🔔 [NOTIFY] Client %s notifié pour commande %d par %s", clientUsername, commandID, staffUsername)
c.JSON(http.StatusOK, gin.H{
"success": true,
"message": "Client notifié",
"client_username": clientUsername,
"success": true,
"message": "Client notifié",
"client_username": clientUsername,
})
}
@@ -989,12 +865,13 @@ func ShowItems(c *gin.Context) {
log.Printf("✅ [ITEMS] %d items récupérés", len(items))
commandInfo := map[string]interface{}{
"id": items[0]["command_id"],
"status": items[0]["command_status"],
"address": items[0]["command_address"],
"total_prix": items[0]["total_prix"],
"livreur": items[0]["livreur_assign"],
"created_at": items[0]["command_created_at"],
"id": items[0]["command_id"],
"status": items[0]["command_status"],
"address": items[0]["command_address"],
"total_prix": items[0]["total_prix"],
"referral_used": items[0]["referral_used"],
"livreur": items[0]["livreur_assign"],
"created_at": items[0]["command_created_at"],
}
clientInfo := map[string]interface{}{
@@ -1098,90 +975,6 @@ func GetCommandItemsWithDetails(c *gin.Context) {
})
}
// GetClientCommandsItems récupère tous les items du client
// GET /api/v1/clients/:username/commands/items
func GetClientCommandsItems(c *gin.Context) {
database := c.MustGet("database").(*db.Database)
username := c.Param("username")
if username == "" {
log.Printf("❌ [CLIENT_ITEMS] Username manquant")
c.JSON(http.StatusBadRequest, gin.H{"error": "Username requis"})
return
}
log.Printf("📦 [CLIENT_ITEMS] Récupération pour: %s", username)
client, err := database.GetClientByUsername(username)
if err != nil {
log.Printf("❌ [CLIENT_ITEMS] Client non trouvé")
c.JSON(http.StatusNotFound, gin.H{"error": "Client non trouvé"})
return
}
items, err := database.GetCommandItemsByUsername(username)
if err != nil {
log.Printf("❌ [CLIENT_ITEMS] Erreur: %v", err)
c.JSON(http.StatusInternalServerError, gin.H{
"error": "Erreur lors de la récupération des items",
"details": err.Error(),
})
return
}
commandsMap := make(map[int][]map[string]interface{})
var commandIDs []int
for _, item := range items {
cmdID := int(item["command_id"].(float64))
if _, exists := commandsMap[cmdID]; !exists {
commandIDs = append(commandIDs, cmdID)
}
commandsMap[cmdID] = append(commandsMap[cmdID], item)
}
log.Printf("✅ [CLIENT_ITEMS] %d items dans %d commandes", len(items), len(commandsMap))
type CommandGroup struct {
CommandID int `json:"command_id"`
Status string `json:"status"`
Address string `json:"address"`
TotalPrice float64 `json:"total_price"`
LivreurAssign string `json:"livreur_assign"`
CreatedAt string `json:"created_at"`
ItemsCount int `json:"items_count"`
Items []map[string]interface{} `json:"items"`
}
var commandGroups []CommandGroup
for _, cmdID := range commandIDs {
items := commandsMap[cmdID]
if len(items) > 0 {
group := CommandGroup{
CommandID: cmdID,
Status: items[0]["command_status"].(string),
Address: items[0]["command_address"].(string),
TotalPrice: items[0]["total_prix"].(float64),
LivreurAssign: fmt.Sprintf("%v", items[0]["livreur_assign"]),
CreatedAt: items[0]["command_created_at"].(string),
ItemsCount: len(items),
Items: items,
}
commandGroups = append(commandGroups, group)
}
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"client": client.Username,
"client_name": fmt.Sprintf("%s %s", client.Prenom, client.Nom),
"phone": client.Telephone,
"total_items": len(items),
"total_commands": len(commandGroups),
"commands": commandGroups,
})
}
// UpdateItemStatus met à jour le statut d'un item
// PUT /api/v1/admin/items/:item_id/status
func UpdateItemStatus(c *gin.Context) {
@@ -1209,7 +1002,7 @@ func UpdateItemStatus(c *gin.Context) {
log.Printf("📝 [UPD_ITEM] Mise à jour: item=%d, status=%s", itemID, req.Status)
validStatuses := []string{"pending", "preparing", "ready", "shipped", "delivered"}
validStatuses := []string{"pending", "preparing", "delivered"}
isValid := false
for _, vs := range validStatuses {
if req.Status == vs {
@@ -1248,65 +1041,6 @@ func UpdateItemStatus(c *gin.Context) {
})
}
// GetCommandFullDetails récupère tous les détails d'une commande
// GET /api/v1/admin/commands/:id/full-details
func GetCommandFullDetails(c *gin.Context) {
database := c.MustGet("database").(*db.Database)
userRole := c.GetString("role")
if userRole != "admin" {
log.Printf("❌ [FULL_DETAILS] Accès refusé - role=%s", userRole)
c.JSON(http.StatusForbidden, gin.H{"error": "Accès refusé - Admin uniquement"})
return
}
commandID, err := strconv.Atoi(c.Param("id"))
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "ID de commande invalide"})
return
}
log.Printf("📋 [FULL_DETAILS] Récupération complète: cmd %d", commandID)
command, err := database.GetCommandByID(commandID)
if err != nil {
log.Printf("❌ [FULL_DETAILS] Non trouvée")
c.JSON(http.StatusNotFound, gin.H{"error": "Commande non trouvée"})
return
}
items, _ := database.GetCommandItems(commandID)
logs, _ := database.GetCommandLogs(commandID)
var clientFullInfo map[string]interface{}
if username, ok := command["username"].(string); ok {
if client, err := database.GetClientByUsername(username); err == nil {
clientFullInfo = map[string]interface{}{
"username": client.Username,
"nom": client.Nom,
"prenom": client.Prenom,
"telephone": client.Telephone,
"commands": client.Command,
"points": client.Point,
"penalties": client.Amende,
"created_at": client.CreatedAt,
}
}
}
log.Printf("✅ [FULL_DETAILS] Récupéré: %d items, %d logs", len(items), len(logs))
c.JSON(http.StatusOK, gin.H{
"success": true,
"command": command,
"client_info": clientFullInfo,
"items": items,
"items_count": len(items),
"logs": logs,
"logs_count": len(logs),
})
}
// DeleteCommandItem supprime un item d'une commande
// DELETE /api/v2/admin/protected/orders/:id/items/:item_id
func DeleteCommandItem(c *gin.Context) {
@@ -1404,65 +1138,3 @@ func UpdateCommandStatusAdmin(c *gin.Context) {
"new_status": req.Status,
})
}
// GetCommandItemsStats récupère les stats d'une commande
// GET /api/v1/commands/:id/stats
func GetCommandItemsStats(c *gin.Context) {
database := c.MustGet("database").(*db.Database)
commandID, err := strconv.Atoi(c.Param("id"))
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "ID invalide"})
return
}
log.Printf("📊 [STATS] Calcul stats: cmd %d", commandID)
items, err := database.GetCommandItems(commandID)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
if len(items) == 0 {
c.JSON(http.StatusOK, gin.H{
"success": true,
"items_count": 0,
"total_items": 0,
"total_price": 0,
"avg_price": 0,
})
return
}
totalItems := 0
totalPrice := 0.0
statusCounts := make(map[string]int)
for _, item := range items {
quantite := int(item["quantite"].(float64))
prix := item["prix"].(float64)
status := item["status"].(string)
totalItems += quantite
totalPrice += prix * float64(quantite)
statusCounts[status]++
}
avgPrice := 0.0
if len(items) > 0 {
avgPrice = totalPrice / float64(len(items))
}
log.Printf("✅ [STATS] Items=%d, Total=%.2f€", totalItems, totalPrice)
c.JSON(http.StatusOK, gin.H{
"success": true,
"command_id": commandID,
"items_count": len(items),
"total_items": totalItems,
"total_price": totalPrice,
"avg_price": avgPrice,
"status_breakdown": statusCounts,
})
}
+18 -14
View File
@@ -158,15 +158,16 @@ func GetDeliveryDetails(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"success": true,
"delivery": gin.H{
"id": command["id"],
"status": command["status"],
"adresse": command["adresse"],
"total_prix": command["total_prix"],
"created_at": command["created_at"],
"client_info": clientInfo,
"items": itemsSummary,
"items_count": len(items),
"eta": etaData,
"id": command["id"],
"status": command["status"],
"adresse": command["adresse"],
"total_prix": command["total_prix"],
"referral_used": command["referral_used"],
"created_at": command["created_at"],
"client_info": clientInfo,
"items": itemsSummary,
"items_count": len(items),
"eta": etaData,
},
})
}
@@ -226,8 +227,7 @@ func UpdateDeliveryStatus(c *gin.Context) {
// ✅ STATUTS VALIDES POUR LIVREUR (correspondant à la DB)
validStatuses := []string{
"support", // Prise en charge
"assigned", // Assigné (si auto-assignation)
"assigned", // Assigné
"en_route", // En route vers le client
"arrived", // Arrivé à destination
"livre", // Livré (en attente confirmation client)
@@ -364,8 +364,6 @@ func UpdateDeliveryStatus(c *gin.Context) {
if clientUsername != "" {
var clientMsg string
switch req.Status {
case "support":
clientMsg = fmt.Sprintf("Votre commande #%d est prise en charge", commandID)
case "en_route":
if etaMinutes > 0 {
clientMsg = fmt.Sprintf("Votre commande #%d est en route ! Arrivée dans ~%d min", commandID, etaMinutes)
@@ -378,6 +376,8 @@ func UpdateDeliveryStatus(c *gin.Context) {
clientMsg = fmt.Sprintf("Votre commande #%d a été livrée. Merci !", commandID)
case "failed":
clientMsg = fmt.Sprintf("Échec de livraison pour la commande #%d", commandID)
case "cancelled":
clientMsg = fmt.Sprintf("Votre commande #%d a été annulée par le livreur", commandID)
}
if clientMsg != "" {
database.NotifyClient(clientUsername, commandID, req.Status, clientMsg)
@@ -404,6 +404,11 @@ func UpdateDeliveryStatus(c *gin.Context) {
usernameStr,
)
case "cancelled":
// Annulation par le livreur - Nettoyer la queue
log.Printf("🚫 Livraison annulée par livreur - Nettoyage queue cmd %d", commandID)
database.CompleteDeliveryAndProcessNext(usernameStr, commandID)
case "arrived":
log.Printf("📍 Livreur arrivé à destination - Commande %d", commandID)
}
@@ -452,7 +457,6 @@ func degreesToRadians(degrees float64) float64 {
func getDeliveryStatusMessage(status string) string {
messages := map[string]string{
"support": "Prise en charge de la livraison",
"assigned": "Commande assignée",
"en_route": "En route vers le client",
"arrived": "Arrivé à destination",
+6 -15
View File
@@ -106,28 +106,19 @@ func GetOrderETA(c *gin.Context) {
return
}
// ✅ CORRECTION CRITIQUE: Vérifier si le livreur a démarré
if cmdStatus != "en_route" && cmdStatus != "arrived" {
log.Printf("⏳ [ETA] Commande en statut '%s' - ETA pas encore disponible", cmdStatus)
livreurAssign, _ := command["livreur_assign"].(string)
var livreurInfo string
if livreurAssign != "" {
livreurInfo = fmt.Sprintf("Livreur %s assigné", livreurAssign)
} else {
livreurInfo = "En attente d'assignation"
}
// Pour pending: aucune estimation disponible
if cmdStatus == "pending" {
log.Printf("⏳ [ETA] Commande en attente d'assignation - pas d'ETA")
c.JSON(http.StatusOK, gin.H{
"success": true,
"command_id": commandID,
"status": cmdStatus,
"message": "Le livreur n'a pas encore démarré la livraison",
"eta_available": false,
"info": livreurInfo,
"message": "En attente d'assignation d'un livreur",
})
return
}
// Pour assigned/en_route/arrived: calcul ETA réel via position du livreur
// 6️⃣ VÉRIFIER LE CACHE REDIS POUR ETA
etaKey := fmt.Sprintf("command:eta:%d", commandID)
@@ -140,7 +131,7 @@ func GetOrderETA(c *gin.Context) {
fmt.Sscanf(updatedAtStr, "%d", &updatedAt)
timeSinceUpdate := time.Since(time.Unix(updatedAt, 0))
if timeSinceUpdate < 2*time.Minute {
if timeSinceUpdate < 30*time.Second {
// Cache valide
var etaMinutes int64
if etaStr, ok := etaData["eta_minutes"]; ok {
+86
View File
@@ -245,6 +245,92 @@ func MarkLivreurNotificationsRead(c *gin.Context) {
})
}
// RegisterAdminPushToken enregistre le push token d'un admin
// POST /api/v2/admin/protected/push-token
func RegisterAdminPushToken(c *gin.Context) {
username := c.GetString("username")
if username == "" {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Non authentifié"})
return
}
var req struct {
PushToken string `json:"push_token" binding:"required"`
}
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "push_token requis"})
return
}
database := c.MustGet("database").(*db.Database)
if err := database.SaveUserPushToken(username, req.PushToken); err != nil {
log.Printf("❌ [ADMIN_PUSH_TOKEN] Erreur sauvegarde pour %s: %v", username, err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "Erreur enregistrement push token"})
return
}
log.Printf("✅ [ADMIN_PUSH_TOKEN] Token enregistré pour admin %s", username)
c.JSON(http.StatusOK, gin.H{"success": true})
}
// UnregisterAdminPushToken supprime le push token d'un admin (au logout)
// DELETE /api/v2/admin/protected/push-token
func UnregisterAdminPushToken(c *gin.Context) {
username := c.GetString("username")
if username == "" {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Non authentifié"})
return
}
database := c.MustGet("database").(*db.Database)
if err := database.DeleteUserPushToken(username); err != nil {
log.Printf("❌ [ADMIN_PUSH_TOKEN] Erreur suppression pour %s: %v", username, err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "Erreur suppression push token"})
return
}
log.Printf("✅ [ADMIN_PUSH_TOKEN] Token supprimé pour admin %s", username)
c.JSON(http.StatusOK, gin.H{"success": true})
}
// RegisterCabinePushToken enregistre le push token d'un agent cabine
// POST /api/v1/cabine/push-token
func RegisterCabinePushToken(c *gin.Context) {
username := c.GetString("username")
if username == "" {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Non authentifié"})
return
}
var req struct {
PushToken string `json:"push_token" binding:"required"`
}
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "push_token requis"})
return
}
database := c.MustGet("database").(*db.Database)
if err := database.SaveUserPushToken(username, req.PushToken); err != nil {
log.Printf("❌ [CABINE_PUSH_TOKEN] Erreur sauvegarde pour %s: %v", username, err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "Erreur enregistrement push token"})
return
}
log.Printf("✅ [CABINE_PUSH_TOKEN] Token enregistré pour cabine %s", username)
c.JSON(http.StatusOK, gin.H{"success": true})
}
// UnregisterCabinePushToken supprime le push token d'un agent cabine (au logout)
// DELETE /api/v1/cabine/push-token
func UnregisterCabinePushToken(c *gin.Context) {
username := c.GetString("username")
if username == "" {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Non authentifié"})
return
}
database := c.MustGet("database").(*db.Database)
if err := database.DeleteUserPushToken(username); err != nil {
log.Printf("❌ [CABINE_PUSH_TOKEN] Erreur suppression pour %s: %v", username, err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "Erreur suppression push token"})
return
}
log.Printf("✅ [CABINE_PUSH_TOKEN] Token supprimé pour cabine %s", username)
c.JSON(http.StatusOK, gin.H{"success": true})
}
// MarkNotificationsRead marque toutes les notifications comme lues
// POST /api/v1/notifications/read
func MarkNotificationsRead(c *gin.Context) {
+70 -10
View File
@@ -319,7 +319,8 @@ func ValidateBasket(c *gin.Context) {
usernameStr := username.(string)
var req struct {
DeliveryAddress string `json:"delivery_address" binding:"required"`
DeliveryAddress string `json:"delivery_address" binding:"required"`
UseReferralBalance bool `json:"use_referral_balance"`
}
if err := c.ShouldBindJSON(&req); err != nil || req.DeliveryAddress == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "Adresse de livraison requise"})
@@ -363,7 +364,16 @@ func ValidateBasket(c *gin.Context) {
}
}
zoneResult := checkDeliveryZone(req.DeliveryAddress, cartTotal)
// Récupérer les paramètres globaux (zones + parrainage)
appSettings, _ := database.GetSettings()
// Récupérer le solde parrainage disponible (seulement si le système est activé)
var referralBalance float64
if req.UseReferralBalance && appSettings.ReferralEnabled {
referralBalance, _ = database.GetClientReferralBalance(usernameStr)
}
zoneResult := checkDeliveryZone(req.DeliveryAddress, cartTotal, appSettings.PostalZones)
if !zoneResult.OK {
if zoneResult.ZoneName == "inconnue" {
log.Printf("❌ [CHECKOUT] Aucun code postal trouvé dans l'adresse: %s", req.DeliveryAddress)
@@ -379,18 +389,41 @@ func ValidateBasket(c *gin.Context) {
} else {
log.Printf("❌ [CHECKOUT] Total %.2f€ insuffisant pour %s (minimum %.2f€)", cartTotal, zoneResult.ZoneName, zoneResult.MinAmount)
c.JSON(http.StatusBadRequest, gin.H{
"error": fmt.Sprintf("Montant minimum de commande non atteint pour votre zone (%.0f€ minimum)", zoneResult.MinAmount),
"zone": zoneResult.ZoneName,
"minimum": zoneResult.MinAmount,
"cart_total": cartTotal,
"missing": zoneResult.MinAmount - cartTotal,
"postal_code": zoneResult.PostalCode,
"error": fmt.Sprintf("Montant minimum de commande non atteint pour votre zone (%.0f€ minimum)", zoneResult.MinAmount),
"zone": zoneResult.ZoneName,
"minimum": zoneResult.MinAmount,
"cart_total": cartTotal,
"missing": zoneResult.MinAmount - cartTotal,
"postal_code": zoneResult.PostalCode,
"referral_balance": referralBalance,
})
}
return
}
log.Printf("✅ [CHECKOUT] Zone OK: %s, total=%.2f€ >= %.2f€", zoneResult.ZoneName, cartTotal, zoneResult.MinAmount)
// Règle parrainage : après déduction du crédit, le client doit toujours payer au minimum le seuil de zone.
// Ex : zone 50€, crédit 50€ → panier doit être >= 100€
var referralUsed float64
if req.UseReferralBalance && referralBalance > 0 {
effectivePayment := cartTotal - referralBalance
if effectivePayment < zoneResult.MinAmount {
needed := zoneResult.MinAmount + referralBalance
log.Printf("❌ [CHECKOUT] Crédit parrainage %.2f€ mais panier insuffisant: %.2f€ < %.2f€ requis", referralBalance, cartTotal, needed)
c.JSON(http.StatusBadRequest, gin.H{
"error": fmt.Sprintf("Avec %.2f€ de crédit parrainage, votre commande doit atteindre %.2f€ (minimum zone %.0f€ + crédit utilisé)", referralBalance, needed, zoneResult.MinAmount),
"zone": zoneResult.ZoneName,
"minimum": needed,
"cart_total": cartTotal,
"missing": needed - cartTotal,
"referral_balance": referralBalance,
"postal_code": zoneResult.PostalCode,
})
return
}
referralUsed = referralBalance
}
log.Printf("✅ [CHECKOUT] Zone OK: %s, total=%.2f€ >= %.2f€, crédit parrainage utilisé: %.2f€", zoneResult.ZoneName, cartTotal, zoneResult.MinAmount, referralUsed)
// ============================================
// 2️⃣ Créer la commande (qui décrémente automatiquement le stock)
@@ -404,6 +437,27 @@ func ValidateBasket(c *gin.Context) {
commandID := command.ID
log.Printf("✅ [CHECKOUT] Commande %d créée", commandID)
// Débiter le solde parrainage si utilisé
if referralUsed > 0 {
tx, txErr := database.Begin()
if txErr == nil {
if txErr = database.UseClientReferralBalance(tx, usernameStr, referralUsed); txErr != nil {
tx.Rollback()
log.Printf("⚠️ [CHECKOUT] Impossible de débiter le crédit parrainage: %v", txErr)
} else {
tx.Commit()
log.Printf("✅ [CHECKOUT] Crédit parrainage -%.2f€ débité pour %s", referralUsed, usernameStr)
// Stocker le montant de parrainage sur la commande
if err := database.SetCommandReferralUsed(commandID, referralUsed); err != nil {
log.Printf("⚠️ [CHECKOUT] Impossible de sauvegarder referral_used sur commande: %v", err)
}
}
}
}
// Notifier immédiatement tous les admins et agents cabine
go database.NotifyAllAdminCabine(commandID, usernameStr, req.DeliveryAddress)
// ============================================
// 3️⃣ Vider le panier
// ============================================
@@ -481,12 +535,15 @@ func ValidateBasket(c *gin.Context) {
// Notifier le livreur de la nouvelle commande
notifMsg := fmt.Sprintf("Nouvelle commande #%d assignée - Livraison dans ~%d min (%.2f km)", commandID, travelTime, distance)
if referralUsed > 0 {
notifMsg += fmt.Sprintf(" | Parrainage client: -%.2f€", referralUsed)
}
if notifErr := database.NotifyLivreur(nearest.Username, commandID, "new_assignment", notifMsg); notifErr != nil {
log.Printf("⚠️ [CHECKOUT] Erreur notification livreur: %v", notifErr)
}
// Notifier le client
clientMsg := fmt.Sprintf("Votre commande #%d est confirmée ! Livraison prévue dans ~%d min", commandID, travelTime)
clientMsg := fmt.Sprintf("Votre commande #%d est confirmée ! Un livreur est en route.", commandID)
database.NotifyClient(usernameStr, commandID, "assigned", clientMsg)
assigned = true
@@ -510,11 +567,14 @@ func ValidateBasket(c *gin.Context) {
// ============================================
// 5️⃣ Réponse
// ============================================
newBalance, _ := database.GetClientReferralBalance(usernameStr)
resp := gin.H{
"success": true,
"command_id": commandID,
"delivery_address": req.DeliveryAddress,
"status": "pending",
"referral_used": referralUsed,
"referral_balance": newBalance,
}
if assigned {
+14 -19
View File
@@ -130,23 +130,18 @@ func validateUnit(unit string) error {
return nil
}
func validateCategory(category string) error {
// Nettoyage
category = strings.ToLower(strings.TrimSpace(category))
category = strings.Map(func(r rune) rune {
if r < 32 || r == 127 {
return -1
}
return r
}, category)
validCategories := []string{"weed&hash", "zipette&co", "gros&semi"}
for _, v := range validCategories {
if category == v {
return nil
}
func validateCategory(database *db.Database, category string) error {
if category == "" {
return fmt.Errorf("catégorie requise")
}
return fmt.Errorf("catégorie invalide")
exists, err := database.CategoryExists(category)
if err != nil {
return fmt.Errorf("erreur vérification catégorie")
}
if !exists {
return fmt.Errorf("catégorie invalide")
}
return nil
}
// ✅ VÉRIFICATION DU TYPE MIME RÉEL (pas juste l'extension)
@@ -246,7 +241,7 @@ func CreateProduct(c *gin.Context) {
return r
}, category)
if err := validateCategory(category); err != nil {
if err := validateCategory(database, category); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
@@ -511,7 +506,7 @@ func GetProductsByCategory(c *gin.Context) {
category := strings.ToLower(strings.TrimSpace(c.Param("category")))
// ✅ VALIDATION
if err := validateCategory(category); err != nil {
if err := validateCategory(database, category); err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"success": false,
"error": err.Error(),
@@ -627,7 +622,7 @@ func UpdateProduct(c *gin.Context) {
return
}
if err := validateCategory(updateData.Category); err != nil {
if err := validateCategory(database, updateData.Category); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
@@ -9,6 +9,7 @@ import (
"encoding/json"
"fmt"
"gestion/db"
"gestion/services"
"log"
"net/http"
"strconv"
@@ -178,6 +179,9 @@ func UpdateLivreurLocation(c *gin.Context) {
log.Printf("📍 Position GPS mise à jour pour %s: (%.6f, %.6f)",
usernameStr, req.Latitude, req.Longitude)
// ✅ Recalculer l'ETA en temps réel si livreur en_route
go refreshETAForActivDelivery(database, usernameStr, req.Latitude, req.Longitude)
// ✅ 2. Vérifier/Initialiser le statut du livreur
statusKey := fmt.Sprintf("delivery:status:%s", usernameStr)
statusData, err := db.Redis.Get(db.RedisCtx, statusKey).Result()
@@ -1049,3 +1053,89 @@ func GetRealtimeStats(c *gin.Context) {
"stats": stats,
})
}
// ============================================
// RECALCUL ETA EN TEMPS RÉEL (appelé à chaque update GPS)
// ============================================
// refreshETAForActivDelivery recalcule l'ETA depuis la position actuelle du livreur.
// Appelé en goroutine à chaque mise à jour GPS (toutes les ~15s).
func refreshETAForActivDelivery(database *db.Database, username string, lat, lon float64) {
// 1. Récupérer le statut actuel du livreur
statusKey := fmt.Sprintf("delivery:status:%s", username)
statusData, err := db.Redis.Get(db.RedisCtx, statusKey).Result()
if err != nil || statusData == "" {
return
}
var status map[string]interface{}
if err := json.Unmarshal([]byte(statusData), &status); err != nil {
return
}
// 2. Seulement si en_route ou arrived
currentStatus, _ := status["status"].(string)
if currentStatus != "en_route" && currentStatus != "arrived" {
return
}
// 3. Récupérer la commande active
var commandID int
switch v := status["current_command"].(type) {
case float64:
commandID = int(v)
case int:
commandID = v
default:
return
}
if commandID <= 0 {
return
}
// 4. Récupérer les coordonnées destination depuis le cache Redis
destCacheKey := fmt.Sprintf("command:destination:%d", commandID)
destData, err := db.Redis.Get(db.RedisCtx, destCacheKey).Result()
if err != nil || destData == "" {
return
}
var coords struct {
Lat float64 `json:"lat"`
Lon float64 `json:"lon"`
}
if err := json.Unmarshal([]byte(destData), &coords); err != nil || coords.Lat == 0 {
return
}
// 5. Calculer l'ETA depuis la position GPS actuelle
from := services.Coordinates{Latitude: lat, Longitude: lon}
to := services.Coordinates{Latitude: coords.Lat, Longitude: coords.Lon}
etaMinutes, distanceKm, err := services.GetETAWithTraffic(from, to)
if err != nil {
// Fallback Haversine uniquement si TomTom indisponible
distanceKm = services.CalculateDistance(from, to)
etaMinutes = services.CalculateETA(distanceKm)
log.Printf("⚠️ [ETA_REALTIME] TomTom indisponible pour %s cmd %d, fallback: %.2fkm → %dmin",
username, commandID, distanceKm, etaMinutes)
} else {
log.Printf("🔄 [ETA_REALTIME] %s cmd %d recalculé: %.2fkm → %dmin (TomTom)",
username, commandID, distanceKm, etaMinutes)
}
// 6. Mettre à jour le cache Redis ETA (écrase l'ancien)
now := time.Now()
arrivalTime := now.Add(time.Duration(etaMinutes) * time.Minute)
etaKey := fmt.Sprintf("command:eta:%d", commandID)
db.Redis.HSet(db.RedisCtx, etaKey, map[string]interface{}{
"command_id": commandID,
"eta_minutes": etaMinutes,
"updated_at": now.Unix(),
"arrival_time": arrivalTime.Unix(),
"distance_km": distanceKm,
"with_traffic": err == nil,
})
db.Redis.Expire(db.RedisCtx, etaKey, 4*time.Hour)
}
+79
View File
@@ -0,0 +1,79 @@
package handlers
import (
"gestion/db"
"log"
"net/http"
"github.com/gin-gonic/gin"
)
// GetMyReferralBalance — GET /api/v1/referral/balance (client)
func GetMyReferralBalance(c *gin.Context) {
database := c.MustGet("database").(*db.Database)
username, exists := c.Get("username")
if !exists {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Utilisateur non authentifié"})
return
}
settings, _ := database.GetSettings()
if !settings.ReferralEnabled {
c.JSON(http.StatusOK, gin.H{"balance": 0, "referral_enabled": false})
return
}
balance, err := database.GetClientReferralBalance(username.(string))
if err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"balance": balance, "referral_enabled": true})
}
// CreditClientReferralAdmin — POST /api/v2/admin/protected/client/:username/referral/credit (admin)
func CreditClientReferralAdmin(c *gin.Context) {
database := c.MustGet("database").(*db.Database)
targetUsername := c.Param("username")
var req struct {
Amount float64 `json:"amount" binding:"required"`
}
if err := c.ShouldBindJSON(&req); err != nil || req.Amount <= 0 {
c.JSON(http.StatusBadRequest, gin.H{"error": "Montant invalide"})
return
}
if err := database.CreditClientReferral(targetUsername, req.Amount); err != nil {
log.Printf("❌ [REFERRAL] Crédit échoué pour %s: %v", targetUsername, err)
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
balance, _ := database.GetClientReferralBalance(targetUsername)
log.Printf("✅ [REFERRAL] +%.2f€ crédité à %s, nouveau solde: %.2f€", req.Amount, targetUsername, balance)
c.JSON(http.StatusOK, gin.H{
"message": "Solde parrainage crédité",
"balance": balance,
})
}
// GetClientReferralAdmin — GET /api/v2/admin/protected/client/:username/referral (admin)
func GetClientReferralAdmin(c *gin.Context) {
database := c.MustGet("database").(*db.Database)
targetUsername := c.Param("username")
balance, err := database.GetClientReferralBalance(targetUsername)
if err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{
"username": targetUsername,
"balance": balance,
})
}
+67
View File
@@ -0,0 +1,67 @@
package handlers
import (
"gestion/db"
"log"
"net/http"
"github.com/gin-gonic/gin"
)
// GET /api/v1/app-settings — public, sans auth
// Retourne uniquement les flags visibles par clients/cabine (pas les détails de catégories)
func GetPublicSettings(c *gin.Context) {
database := c.MustGet("database").(*db.Database)
settings, err := database.GetSettings()
if err != nil {
// En cas d'erreur, retourner les valeurs par défaut
settings = db.DefaultSettings()
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"penalties_enabled": settings.PenaltiesEnabled,
"show_amende_score": settings.ShowAmendeScore,
"points_enabled": settings.PointsEnabled,
"points_separated": settings.PointsSeparated,
"referral_enabled": settings.ReferralEnabled,
"delivery_schedule": settings.DeliverySchedule,
})
}
// GET /api/v2/admin/protected/settings
func GetSettings(c *gin.Context) {
database := c.MustGet("database").(*db.Database)
settings, err := database.GetSettings()
if err != nil {
log.Printf("❌ [SETTINGS] Erreur lecture: %v", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "Erreur lecture paramètres"})
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "settings": settings})
}
// PUT /api/v2/admin/protected/settings
func UpdateSettings(c *gin.Context) {
database := c.MustGet("database").(*db.Database)
var req db.AppSettings
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Paramètres invalides"})
return
}
if err := database.UpdateSettings(req); err != nil {
log.Printf("❌ [SETTINGS] Erreur mise à jour: %v", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "Erreur mise à jour paramètres"})
return
}
log.Printf("✅ [SETTINGS] Mise à jour: penalties=%v, points_separated=%v, weed=%v, zipette=%v, total=%v",
req.PenaltiesEnabled, req.PointsSeparated, req.PointsCategoriesWeed, req.PointsCategoriesZipette, req.PointsCategoriesTotal)
c.JSON(http.StatusOK, gin.H{"success": true, "settings": req})
}
-572
View File
@@ -6,565 +6,9 @@ package handlers
import (
"encoding/json"
"fmt"
"gestion/db"
"gestion/models"
"gestion/services"
"io"
"log"
"math"
"net/http"
"os"
"strconv"
"time"
"github.com/gin-gonic/gin"
)
// ============================================
// INCIDENTS TRAFFIC TOMTOM
// ============================================
// GetIncidentsAroundDeliveryPerson récupère les incidents autour d'un livreur
// GET /api/v2/admin/traffic/delivery/:username/incidents
func GetIncidentsAroundDeliveryPerson(c *gin.Context) {
database := c.MustGet("database").(*db.Database)
userRole := c.GetString("role")
if userRole != "admin" && userRole != "livreur" {
c.JSON(http.StatusForbidden, gin.H{"error": "Accès refusé"})
return
}
username := c.Param("username")
if username == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "Username requis"})
return
}
// Récupérer position du livreur
lat, lon, err := database.GetDeliveryPersonLocation(username)
if err != nil {
c.JSON(http.StatusNotFound, gin.H{
"error": "Position livreur non trouvée",
"details": err.Error(),
})
return
}
// Rayon de recherche par défaut: 5 km
radius := 5000 // mètres
// Récupérer incidents TomTom
incidents, err := fetchIncidents(lat, lon, radius)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": "Erreur récupération incidents",
"details": err.Error(),
})
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"username": username,
"location": gin.H{"latitude": lat, "longitude": lon},
"radius_km": radius / 1000,
"incidents": incidents,
"count": len(incidents),
})
}
// GetIncidentsForAllDeliveries récupère incidents + routes pour tous livreurs actifs
// GET /api/v2/admin/traffic/incidents/all
func GetIncidentsForAllDeliveries(c *gin.Context) {
database := c.MustGet("database").(*db.Database)
userRole := c.GetString("role")
if userRole != "admin" {
c.JSON(http.StatusForbidden, gin.H{"error": "Accès refusé"})
return
}
// Récupérer tous les livreurs disponibles depuis Redis
livreurs, err := database.GetAvailableDeliveryPersonsRedis()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": "Erreur récupération livreurs",
"details": err.Error(),
})
return
}
results := []gin.H{}
for _, livreur := range livreurs {
username := livreur.Username
status := livreur.Status
// Sauter les livreurs offline
if status == "offline" {
continue
}
// Position livreur
lat, lon, err := database.GetDeliveryPersonLocation(username)
if err != nil {
log.Printf("⚠️ Position non trouvée pour %s", username)
continue
}
// Vérifier s'il a une commande en cours
commandID := livreur.CurrentCommand
if commandID == 0 {
// Pas de livraison en cours
results = append(results, gin.H{
"username": username,
"status": status,
"location": gin.H{"latitude": lat, "longitude": lon},
"has_delivery": false,
"incidents": []gin.H{},
"route": nil,
})
continue
}
// Récupérer la commande
command, err := database.GetCommandByID(commandID)
if err != nil {
log.Printf("⚠️ Commande %d non trouvée", commandID)
continue
}
// Coordonnées destination
var destLat, destLon float64
if dLat, ok := getFloatFromMap(command, "dest_latitude"); ok && dLat != 0 {
destLat = dLat
}
if dLon, ok := getFloatFromMap(command, "dest_longitude"); ok && dLon != 0 {
destLon = dLon
}
// Si pas de coordonnées, géocoder
if destLat == 0 || destLon == 0 {
address, ok := command["adresse"].(string)
if !ok || address == "" || address == "Adresse non spécifiée" {
continue
}
geoService := c.MustGet("geoService").(*services.GeoService)
location, err := geoService.GeocodeAddress(address)
if err != nil {
log.Printf("⚠️ Géocodage échoué pour %s", address)
continue
}
destLat = location.Latitude
destLon = location.Longitude
}
// Récupérer incidents sur le trajet
incidents, _ := fetchIncidentsOnRoute(lat, lon, destLat, destLon)
// Convertir incidents en gin.H pour JSON
incidentsJSON := make([]gin.H, len(incidents))
for i, inc := range incidents {
incidentsJSON[i] = gin.H{
"type": inc.Type,
"icon": inc.Icon,
"description": inc.Description,
}
}
// Calculer route avec trafic
routeSummary, err := fetchRouteSummary(lat, lon, destLat, destLon)
if err != nil {
log.Printf("⚠️ Erreur calcul route pour %s", username)
routeSummary = models.RouteSummary{}
}
results = append(results, gin.H{
"username": username,
"status": status,
"location": gin.H{"latitude": lat, "longitude": lon},
"destination": gin.H{"latitude": destLat, "longitude": destLon},
"has_delivery": true,
"command_id": commandID,
"incidents": incidentsJSON,
"route": routeSummary,
})
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"deliveries": results,
"count": len(results),
})
}
// ============================================
// MISE À JOUR ETA AVEC TRAFIC
// ============================================
func UpdateETAWithRealTraffic(c *gin.Context) {
database := c.MustGet("database").(*db.Database)
userRole := c.GetString("role")
if userRole != "admin" && userRole != "livreur" {
c.JSON(http.StatusForbidden, gin.H{"error": "Accès refusé"})
return
}
// Récupérer l'ID de la commande
commandID, err := strconv.Atoi(c.Param("id"))
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "ID invalide"})
return
}
// Récupérer la commande
command, err := database.GetCommandByID(commandID)
if err != nil {
c.JSON(http.StatusNotFound, gin.H{
"error": "Commande non trouvée",
"command_id": commandID,
})
return
}
// Vérifier qu'un livreur est assigné
livreurAssign, ok := command["livreur_assign"].(string)
if !ok || livreurAssign == "" {
c.JSON(http.StatusBadRequest, gin.H{
"error": "Aucun livreur assigné",
"command_id": commandID,
})
return
}
// Position actuelle du livreur
lat, lon, err := database.GetDeliveryPersonLocation(livreurAssign)
if err != nil {
c.JSON(http.StatusNotFound, gin.H{
"error": "Position livreur introuvable",
"livreur": livreurAssign,
"details": err.Error(),
})
return
}
var destLat, destLon float64
// 🔹 1. Tenter de récupérer depuis le cache Redis (clé spécifique pour destination)
destCacheKey := fmt.Sprintf("command:destination:%d", commandID)
destData, err := db.Redis.Get(db.RedisCtx, destCacheKey).Result()
if err == nil && destData != "" {
var coords struct {
Lat float64 `json:"lat"`
Lon float64 `json:"lon"`
}
if err := json.Unmarshal([]byte(destData), &coords); err == nil && coords.Lat != 0 && coords.Lon != 0 {
destLat = coords.Lat
destLon = coords.Lon
log.Printf("📍 Destination trouvée dans cache Redis pour commande %d", commandID)
}
}
// 🔹 2. Fallback: récupérer depuis la DB
if destLat == 0 || destLon == 0 {
if dLat, okLat := getFloatFromMap(command, "dest_latitude"); okLat && dLat != 0 {
destLat = dLat
}
if dLon, okLon := getFloatFromMap(command, "dest_longitude"); okLon && dLon != 0 {
destLon = dLon
}
}
// 🔹 3. Si toujours pas de coordonnées, géocoder l'adresse
if destLat == 0 || destLon == 0 {
address, ok := command["adresse"].(string)
if !ok || address == "" || address == "Adresse non spécifiée" {
c.JSON(http.StatusBadRequest, gin.H{
"error": "Adresse de destination manquante ou invalide",
"command_id": commandID,
})
return
}
geoService := c.MustGet("geoService").(*services.GeoService)
location, err := geoService.GeocodeAddress(address)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": "Impossible de géocoder l'adresse",
"address": address,
"command_id": commandID,
"details": err.Error(),
})
return
}
destLat = location.Latitude
destLon = location.Longitude
log.Printf("📍 Adresse géocodée pour commande %d: %s -> (%.6f, %.6f)",
commandID, address, destLat, destLon)
}
// 🔹 4. Sauvegarder les coordonnées destination dans le cache Redis
coordsJSON, _ := json.Marshal(map[string]float64{
"lat": destLat,
"lon": destLon,
})
if err := db.Redis.Set(db.RedisCtx, destCacheKey, coordsJSON, 4*time.Hour).Err(); err != nil {
log.Printf("⚠️ Impossible de sauvegarder destination dans Redis: %v", err)
}
// 🔹 5. Calculer le temps réel avec TomTom Routing API
routeSummary, err := fetchRouteSummary(lat, lon, destLat, destLon)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": "Impossible de calculer l'itinéraire",
"command_id": commandID,
"from": gin.H{"lat": lat, "lon": lon},
"to": gin.H{"lat": destLat, "lon": destLon},
"details": err.Error(),
})
return
}
// 🔹 6. Mettre à jour l'ETA dans Redis
err = database.SetCommandETA(commandID, routeSummary.TravelTimeInMinutes)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": "Erreur mise à jour ETA",
"command_id": commandID,
"details": err.Error(),
})
return
}
log.Printf("✅ ETA mis à jour pour commande %d: %d min (trafic réel inclus)",
commandID, routeSummary.TravelTimeInMinutes)
c.JSON(http.StatusOK, gin.H{
"success": true,
"command_id": commandID,
"eta_minutes": routeSummary.TravelTimeInMinutes,
"distance_km": routeSummary.LengthInKm,
"with_traffic": true,
"route_summary": routeSummary,
})
}
// ============================================
// FONCTIONS HELPERS - TOMTOM API
// ============================================
// fetchIncidents récupère les incidents de trafic autour d'une position
func fetchIncidents(lat, lon float64, radius int) ([]models.Incident, error) {
apiKey := os.Getenv("TOMTOM_API_KEY")
if apiKey == "" {
return nil, fmt.Errorf("TOMTOM_API_KEY non configurée")
}
// API TomTom Traffic Incidents
url := fmt.Sprintf(
"https://api.tomtom.com/traffic/services/5/incidentDetails?key=%s&bbox=%f,%f,%f,%f&fields={incidents{type,geometry{type,coordinates},properties{iconCategory,magnitudeOfDelay,events{description,code,iconCategory}}}}",
apiKey,
lon-0.05, lat-0.05, // Southwest corner
lon+0.05, lat+0.05, // Northeast corner
)
client := &http.Client{Timeout: 10 * time.Second}
resp, err := client.Get(url)
if err != nil {
return nil, fmt.Errorf("erreur requête incidents: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return nil, fmt.Errorf("API incidents error %d: %s", resp.StatusCode, string(body))
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("erreur lecture réponse: %w", err)
}
var incidentResponse models.IncidentResponse
err = json.Unmarshal(body, &incidentResponse)
if err != nil {
return nil, fmt.Errorf("erreur parsing incidents: %w", err)
}
// Convertir en []models.Incident
incidents := make([]models.Incident, len(incidentResponse.Incidents))
for i, inc := range incidentResponse.Incidents {
incidents[i] = models.Incident{
Type: inc.Type,
Icon: inc.Icon,
Description: inc.Description,
}
}
return incidents, nil
}
// fetchIncidentsOnRoute récupère les incidents sur un trajet
func fetchIncidentsOnRoute(startLat, startLon, destLat, destLon float64) ([]models.Incident, error) {
// Calculer la bounding box du trajet
minLat := min(startLat, destLat) - 0.02
maxLat := max(startLat, destLat) + 0.02
minLon := min(startLon, destLon) - 0.02
maxLon := max(startLon, destLon) + 0.02
apiKey := os.Getenv("TOMTOM_API_KEY")
if apiKey == "" {
return []models.Incident{}, nil
}
url := fmt.Sprintf(
"https://api.tomtom.com/traffic/services/5/incidentDetails?key=%s&bbox=%f,%f,%f,%f&fields={incidents{type,geometry{type,coordinates},properties{iconCategory,magnitudeOfDelay,events{description,code,iconCategory}}}}",
apiKey,
minLon, minLat,
maxLon, maxLat,
)
client := &http.Client{Timeout: 10 * time.Second}
resp, err := client.Get(url)
if err != nil {
return []models.Incident{}, nil
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return []models.Incident{}, nil
}
body, _ := io.ReadAll(resp.Body)
var incidentResponse models.IncidentResponse
if err := json.Unmarshal(body, &incidentResponse); err != nil {
return []models.Incident{}, nil
}
// Convertir en []models.Incident
incidents := make([]models.Incident, len(incidentResponse.Incidents))
for i, inc := range incidentResponse.Incidents {
incidents[i] = models.Incident{
Type: inc.Type,
Icon: inc.Icon,
Description: inc.Description,
}
}
return incidents, nil
}
// récupère le temps de trajet réel via l'API TomTom Routing
// fetchRouteSummary récupère le temps de trajet réel via l'API TomTom Routing
func fetchRouteSummary(startLat, startLon, destLat, destLon float64) (models.RouteSummary, error) {
apiKey := os.Getenv("TOMTOM_API_KEY")
if apiKey == "" {
return models.RouteSummary{}, fmt.Errorf("TOMTOM_API_KEY non configurée")
}
// Validation des coordonnées
if startLat < -90 || startLat > 90 || destLat < -90 || destLat > 90 {
return models.RouteSummary{}, fmt.Errorf("latitude invalide: start=%.6f, dest=%.6f", startLat, destLat)
}
if startLon < -180 || startLon > 180 || destLon < -180 || destLon > 180 {
return models.RouteSummary{}, fmt.Errorf("longitude invalide: start=%.6f, dest=%.6f", startLon, destLon)
}
// API TomTom Routing: Calculate Route
url := fmt.Sprintf(
"https://api.tomtom.com/routing/1/calculateRoute/%f,%f:%f,%f/json?key=%s&traffic=true&travelMode=car",
startLat, startLon, destLat, destLon, apiKey,
)
log.Printf("🛣️ Appel TomTom: (%.6f,%.6f) -> (%.6f,%.6f)", startLat, startLon, destLat, destLon)
// Timeout réduit à 8 secondes
client := &http.Client{Timeout: 8 * time.Second}
resp, err := client.Get(url)
if err != nil {
// Fallback: estimation basée sur distance Haversine
distance := haversineDistance(startLat, startLon, destLat, destLon)
estimatedMinutes := int(distance/25*60) + 3 // ~25 km/h en ville + 3 min marge
if estimatedMinutes < 5 {
estimatedMinutes = 5
}
log.Printf("⚠️ TomTom timeout/erreur, fallback: %.2f km -> %d min estimé", distance, estimatedMinutes)
return models.RouteSummary{
TravelTimeInMinutes: estimatedMinutes,
LengthInKm: distance,
}, nil // Pas d'erreur, on retourne l'estimation
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
io.ReadAll(resp.Body) // Lire et ignorer le body pour fermer proprement
// Fallback en cas d'erreur API
distance := haversineDistance(startLat, startLon, destLat, destLon)
estimatedMinutes := int(distance/25*60) + 3
if estimatedMinutes < 5 {
estimatedMinutes = 5
}
log.Printf("⚠️ TomTom API error %d, fallback: %.2f km -> %d min", resp.StatusCode, distance, estimatedMinutes)
return models.RouteSummary{
TravelTimeInMinutes: estimatedMinutes,
LengthInKm: distance,
}, nil
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return models.RouteSummary{}, fmt.Errorf("erreur lecture réponse: %w", err)
}
var routeResponse models.RouteResponse
err = json.Unmarshal(body, &routeResponse)
if err != nil {
return models.RouteSummary{}, fmt.Errorf("erreur parsing routing: %w", err)
}
if len(routeResponse.Routes) == 0 {
return models.RouteSummary{}, fmt.Errorf("aucun itinéraire trouvé")
}
summary := routeResponse.Routes[0].Summary
summary.TravelTimeInMinutes = (summary.TravelTimeInSeconds + 59) / 60
summary.LengthInKm = float64(summary.LengthInMeters) / 1000.0
log.Printf("🛣️ Route calculée: %.2f km, %d min (trafic inclus)", summary.LengthInKm, summary.TravelTimeInMinutes)
return summary, nil
}
// haversineDistance calcule la distance en km entre deux points GPS
func haversineDistance(lat1, lon1, lat2, lon2 float64) float64 {
const R = 6371.0 // Rayon Terre en km
const toRad = math.Pi / 180.0
dLat := (lat2 - lat1) * toRad
dLon := (lon2 - lon1) * toRad
a := math.Sin(dLat/2)*math.Sin(dLat/2) +
math.Cos(lat1*toRad)*math.Cos(lat2*toRad)*
math.Sin(dLon/2)*math.Sin(dLon/2)
c := 2 * math.Atan2(math.Sqrt(a), math.Sqrt(1-a))
return R * c
}
// getFloatFromMap récupère un float64 depuis une map avec différents types
func getFloatFromMap(m map[string]interface{}, key string) (float64, bool) {
value, exists := m[key]
@@ -606,19 +50,3 @@ func getFloatFromMap(m map[string]interface{}, key string) (float64, bool) {
return 0, false
}
}
// min retourne le minimum entre deux float64
func min(a, b float64) float64 {
if a < b {
return a
}
return b
}
// max retourne le maximum entre deux float64
func max(a, b float64) float64 {
if a > b {
return a
}
return b
}
@@ -1,11 +1,3 @@
// ============================================
// handlers/delivery_validation_handler.go - CLEAN VERSION
// VALIDATION LIVRAISON AVEC VÉRIFICATION PROXIMITÉ GPS
//
// ⚠️ IMPORTANT: Ce fichier contient UNIQUEMENT les fonctions livreur
// Les fonctions ADMIN sont dans cabine_handlers.go
// ============================================
package handlers
import (
@@ -358,11 +350,11 @@ func StartDelivery(c *gin.Context) {
// Vérifier le statut actuel
currentStatus, _ := command["status"].(string)
if currentStatus != "support" && currentStatus != "assigned" {
if currentStatus != "assigned" {
c.JSON(http.StatusBadRequest, gin.H{
"error": "Impossible de démarrer cette livraison",
"current_status": currentStatus,
"message": "La commande doit être en statut 'support' ou 'assigned'",
"message": "La commande doit être en statut 'assigned'",
})
return
}
+11 -76
View File
@@ -1,66 +1,9 @@
package handlers
import "regexp"
// ============================================================
// Zones de livraison — minimum de commande par code postal
// ============================================================
// Remplis les listes de codes postaux quand tu les as.
// Un code postal absent de toutes les zones → commande refusée.
// ============================================================
type deliveryZone struct {
Name string
MinAmount float64
codes map[string]struct{}
}
var deliveryZones = []deliveryZone{
{
Name: "Zone 30€",
MinAmount: 30.0,
codes: postalSet([]string{
"44000",
"44100",
"44200",
"44300",
}),
},
{
Name: "Zone 50€",
MinAmount: 50.0,
codes: postalSet([]string{
"44400", // Rezé
"44880", // Les Sorinières / Sautron
"44120", // Vertou
"44230", // Saint-Sébastien-sur-Loire
"44115", // Basse-Goulaine / Haute-Goulaine
"44980", // Sainte-Luce-sur-Loire
"44470", // Carquefou
"44240", // La Chapelle-sur-Erdre
"44700", // Orvault
"44800", // Saint-Herblain
"44340", // Bouguenais
"44620", // La Montagne
"44830", // Bouaye
}),
},
{
Name: "Zone 100€",
MinAmount: 100.0,
codes: postalSet([]string{
"44860", // Pont-Saint-Martin / Saint-Aignan-Grandlieu
"44220", // Couëron
"44118", // La Chevrolière
"44830", // Brains
"44710", // Saint-Léger-les-Vignes
"44690", // La Haie-Fouassière
"44470", // Mauves-sur-Loire
"44240", // Sucé-sur-Erdre
"44119", // Grandchamp-des-Fontaines
}),
},
}
import (
"gestion/db"
"regexp"
)
var postalCodeRe = regexp.MustCompile(`\b(\d{5})\b`)
@@ -91,21 +34,18 @@ type zoneCheckResult struct {
}
// checkDeliveryZone vérifie si le total respecte le minimum de la zone de l'adresse.
// Les zones sont lues depuis la DB (settings.PostalZones).
// Code postal introuvable → OK = false (refus).
// Code postal hors de toutes les zones → OK = false (refus).
func checkDeliveryZone(deliveryAddress string, total float64) zoneCheckResult {
func checkDeliveryZone(deliveryAddress string, total float64, zones []db.PostalZone) zoneCheckResult {
code := extractPostalCode(deliveryAddress)
if code == "" {
return zoneCheckResult{
PostalCode: "",
ZoneName: "inconnue",
MinAmount: 0,
OK: false,
}
return zoneCheckResult{PostalCode: "", ZoneName: "inconnue", MinAmount: 0, OK: false}
}
for _, zone := range deliveryZones {
if _, found := zone.codes[code]; found {
for _, zone := range zones {
set := postalSet(zone.Codes)
if _, found := set[code]; found {
return zoneCheckResult{
PostalCode: code,
ZoneName: zone.Name,
@@ -115,10 +55,5 @@ func checkDeliveryZone(deliveryAddress string, total float64) zoneCheckResult {
}
}
return zoneCheckResult{
PostalCode: code,
ZoneName: "hors zone",
MinAmount: 0,
OK: false,
}
return zoneCheckResult{PostalCode: code, ZoneName: "hors zone", MinAmount: 0, OK: false}
}