package handlers import ( "fmt" "gestion/db" "log" "net/http" "strconv" "github.com/gin-gonic/gin" ) // GetMyCompletedOrdersWithItems récupère l'historique avec les détails des items // GET /api/v1/my-commands/history/detailed func GetMyCompletedOrdersWithItems(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("❌ [HISTORY_DETAILED] Utilisateur non authentifié") c.JSON(http.StatusUnauthorized, gin.H{ "error": "Authentification requise", }) return } usernameStr := username.(string) log.Printf("📚 [HISTORY_DETAILED] Récupération historique détaillé pour: %s", usernameStr) // ✅ Récupérer les commandes terminées commands, err := database.GetCompletedCommandsByUsername(usernameStr) if err != nil { log.Printf("❌ [HISTORY_DETAILED] Erreur: %v", err) c.JSON(http.StatusInternalServerError, gin.H{ "error": "Erreur lors de la récupération de l'historique", }) return } // ✅ Enrichir chaque commande avec ses items var enrichedCommands []map[string]any for _, command := range commands { commandID, _ := strconv.Atoi(fmt.Sprintf("%v", command["id"])) if commandID == 0 { continue } // Récupérer les items de cette commande items, err := database.GetCommandItems(commandID) if err != nil { log.Printf("⚠️ [HISTORY_DETAILED] Erreur items pour cmd %d: %v", commandID, err) items = []map[string]any{} } // Ajouter les items à la commande enrichedCommand := make(map[string]any) for k, v := range command { enrichedCommand[k] = v } enrichedCommand["items"] = items enrichedCommand["items_count"] = len(items) enrichedCommands = append(enrichedCommands, enrichedCommand) } log.Printf("✅ [HISTORY_DETAILED] %d commandes enrichies", len(enrichedCommands)) // ✅ Récupérer les infos client client, err := database.GetClientByUsername(usernameStr) response := gin.H{ "success": true, "commands": enrichedCommands, "count": len(enrichedCommands), } if err == nil && client != nil { response["client_stats"] = gin.H{ "username": client.Username, "nom": client.Nom, "prenom": client.Prenom, "telephone": client.Telephone, "total_commands": client.Command, "points_extra": client.PointsExtra, "penalties": client.Amende, } } c.JSON(http.StatusOK, response) } func GetOrderHistory(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("❌ [ORDER_HISTORY] Utilisateur non authentifié") c.JSON(http.StatusUnauthorized, gin.H{ "error": "Authentification requise", }) return } usernameStr := username.(string) // Récupérer l'ID de la commande var commandID int if _, err := fmt.Sscanf(c.Param("id"), "%d", &commandID); err != nil { c.JSON(http.StatusBadRequest, gin.H{ "error": "ID de commande invalide", }) return } log.Printf("📜 [ORDER_HISTORY] Récupération historique cmd %d pour %s", commandID, usernameStr) // ✅ Vérifier que la commande existe command, err := database.GetCommandByID(commandID) if err != nil { log.Printf("❌ [ORDER_HISTORY] Commande non trouvée") c.JSON(http.StatusNotFound, gin.H{ "error": "Commande non trouvée", }) return } // ✅ Vérifier que la commande appartient au client cmdUsername, ok := command["username"].(string) if !ok || cmdUsername != usernameStr { log.Printf("❌ [ORDER_HISTORY] Accès refusé - cmd appartient à %s, pas à %s", cmdUsername, usernameStr) c.JSON(http.StatusForbidden, gin.H{ "error": "Cette commande ne vous appartient pas", }) return } // ✅ Récupérer les logs de la commande logs, err := database.GetCommandLogs(commandID) if err != nil { log.Printf("⚠️ [ORDER_HISTORY] Erreur logs: %v", err) logs = []map[string]interface{}{} } // ✅ Récupérer les items items, err := database.GetCommandItems(commandID) if err != nil { log.Printf("⚠️ [ORDER_HISTORY] Erreur items: %v", err) items = []map[string]interface{}{} } log.Printf("✅ [ORDER_HISTORY] Cmd %d: %d logs, %d items", commandID, len(logs), len(items)) c.JSON(http.StatusOK, gin.H{ "success": true, "command": command, "logs": logs, "logs_count": len(logs), "items": items, "items_count": len(items), }) }