chore: build
This commit is contained in:
@@ -76,8 +76,9 @@ func (d *Database) GetClientByID(id int) (*models.Client, error) {
|
||||
return client, nil
|
||||
}
|
||||
|
||||
// GetAllClients récupère tous les clients
|
||||
func (d *Database) GetAllClients() ([]*models.Client, error) {
|
||||
// GetAllClients récupère une page de clients, triée par date de création
|
||||
// descendante, ainsi que le nombre total de clients en base.
|
||||
func (d *Database) GetAllClients(limit, offset int) ([]*models.Client, int64, error) {
|
||||
var rows []struct {
|
||||
ID int `gorm:"column:id"`
|
||||
Username string `gorm:"column:username"`
|
||||
@@ -89,16 +90,25 @@ func (d *Database) GetAllClients() ([]*models.Client, error) {
|
||||
Amende float64 `gorm:"column:amende"`
|
||||
ReferralBalance float64 `gorm:"column:referral_balance"`
|
||||
CancellationsCount int `gorm:"column:cancellations_count"`
|
||||
LastPenaltyReason string `gorm:"column:last_penalty_reason"`
|
||||
Parrain string `gorm:"column:parrain"`
|
||||
PointsExtraJSON []byte `gorm:"column:points_extra"`
|
||||
CreatedAt time.Time `gorm:"column:created_at"`
|
||||
}
|
||||
err := d.GDB.Raw(`
|
||||
SELECT id, username, password, nom, prenom, telephone, command, amende, referral_balance,
|
||||
COALESCE(cancellations_count, 0) as cancellations_count,
|
||||
COALESCE(last_penalty_reason, '') as last_penalty_reason,
|
||||
COALESCE(parrain, '') as parrain,
|
||||
COALESCE(points_extra, '{}'::jsonb) as points_extra, created_at
|
||||
FROM clients ORDER BY created_at DESC`).Scan(&rows).Error
|
||||
FROM clients ORDER BY created_at DESC LIMIT ? OFFSET ?`, limit, offset).Scan(&rows).Error
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("erreur lors de la récupération des clients: %w", err)
|
||||
return nil, 0, fmt.Errorf("erreur lors de la récupération des clients: %w", err)
|
||||
}
|
||||
|
||||
var total int64
|
||||
if err := d.GDB.Table("clients").Count(&total).Error; err != nil {
|
||||
return nil, 0, fmt.Errorf("erreur lors du comptage des clients: %w", err)
|
||||
}
|
||||
|
||||
clients := make([]*models.Client, 0, len(rows))
|
||||
@@ -114,6 +124,8 @@ func (d *Database) GetAllClients() ([]*models.Client, error) {
|
||||
Amende: row.Amende,
|
||||
ReferralBalance: row.ReferralBalance,
|
||||
CancellationsCount: row.CancellationsCount,
|
||||
LastPenaltyReason: row.LastPenaltyReason,
|
||||
Parrain: row.Parrain,
|
||||
CreatedAt: row.CreatedAt,
|
||||
}
|
||||
client.PointsExtra = map[string]int{}
|
||||
@@ -123,7 +135,7 @@ func (d *Database) GetAllClients() ([]*models.Client, error) {
|
||||
clients = append(clients, client)
|
||||
}
|
||||
|
||||
return clients, nil
|
||||
return clients, total, nil
|
||||
}
|
||||
|
||||
// UpdateClient met à jour un client existant
|
||||
|
||||
@@ -6,10 +6,13 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
var allowedStatuses = map[string]bool{
|
||||
@@ -98,6 +101,138 @@ func ValidateStatuses(statuses string) ([]string, error) {
|
||||
return cleanStatuses, nil
|
||||
}
|
||||
|
||||
// DeliveryPersonDetails regroupe les infos enrichies d'un livreur pour un
|
||||
// affichage en liste (statut, position, queue, compteurs de livraisons).
|
||||
type DeliveryPersonDetails struct {
|
||||
Status string
|
||||
HasLocation bool
|
||||
Latitude float64
|
||||
Longitude float64
|
||||
LocationLastUpdate int64
|
||||
QueueSize int
|
||||
CurrentCommand int
|
||||
TotalDeliveries int
|
||||
CompletedDeliveries int
|
||||
PendingDeliveries int
|
||||
}
|
||||
|
||||
// GetDeliveryPersonsDetailsBatch récupère les infos enrichies de plusieurs
|
||||
// livreurs en quelques allers-retours Redis/DB au lieu d'une requête
|
||||
// complète par livreur (l'ancien pattern faisait ~6-8 requêtes par livreur :
|
||||
// GetUserByUsername + 2 lectures Redis + GetDeliverymanQueueSize +
|
||||
// GetCurrentCommand + 3 COUNT(*) séparés, répété pour chaque livreur de la
|
||||
// liste — coûteux dès que ces écrans sont rafraîchis en polling).
|
||||
func (d *Database) GetDeliveryPersonsDetailsBatch(usernames []string) map[string]*DeliveryPersonDetails {
|
||||
result := make(map[string]*DeliveryPersonDetails, len(usernames))
|
||||
for _, u := range usernames {
|
||||
result[u] = &DeliveryPersonDetails{Status: "offline"}
|
||||
}
|
||||
if len(usernames) == 0 {
|
||||
return result
|
||||
}
|
||||
|
||||
statusKeys := make([]string, len(usernames))
|
||||
currentKeys := make([]string, len(usernames))
|
||||
locationKeys := make([]string, len(usernames))
|
||||
for i, u := range usernames {
|
||||
statusKeys[i] = fmt.Sprintf("delivery:status:%s", u)
|
||||
currentKeys[i] = fmt.Sprintf("delivery:current:%s", u)
|
||||
locationKeys[i] = fmt.Sprintf("delivery:location:%s", u)
|
||||
}
|
||||
|
||||
// MGET regroupe la lecture de toutes les clés d'un type en un seul
|
||||
// aller-retour Redis, quel que soit le nombre de livreurs.
|
||||
if statuses, err := Redis.MGet(RedisCtx, statusKeys...).Result(); err == nil {
|
||||
for i, v := range statuses {
|
||||
if s, ok := v.(string); ok && s != "" {
|
||||
result[usernames[i]].Status = s
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if currents, err := Redis.MGet(RedisCtx, currentKeys...).Result(); err == nil {
|
||||
for i, v := range currents {
|
||||
s, ok := v.(string)
|
||||
if !ok || s == "" {
|
||||
continue
|
||||
}
|
||||
var id int
|
||||
if _, err := fmt.Sscanf(s, "%d", &id); err == nil {
|
||||
result[usernames[i]].CurrentCommand = id
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if locations, err := Redis.MGet(RedisCtx, locationKeys...).Result(); err == nil {
|
||||
for i, v := range locations {
|
||||
s, ok := v.(string)
|
||||
if !ok || s == "" {
|
||||
continue
|
||||
}
|
||||
var loc struct {
|
||||
Latitude float64 `json:"latitude"`
|
||||
Longitude float64 `json:"longitude"`
|
||||
LastUpdate int64 `json:"last_update"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(s), &loc); err == nil {
|
||||
det := result[usernames[i]]
|
||||
det.HasLocation = true
|
||||
det.Latitude = loc.Latitude
|
||||
det.Longitude = loc.Longitude
|
||||
det.LocationLastUpdate = loc.LastUpdate
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// LLEN ne se groupe pas via MGET (ce n'est pas une clé string) : un
|
||||
// pipeline permet quand même de n'envoyer qu'un seul aller-retour réseau
|
||||
// pour les N commandes LLEN.
|
||||
pipe := Redis.Pipeline()
|
||||
queueCmds := make([]*redis.IntCmd, len(usernames))
|
||||
for i, u := range usernames {
|
||||
queueCmds[i] = pipe.LLen(RedisCtx, fmt.Sprintf("delivery:queue:%s", u))
|
||||
}
|
||||
if _, err := pipe.Exec(RedisCtx); err == nil {
|
||||
for i, cmd := range queueCmds {
|
||||
if n, err := cmd.Result(); err == nil {
|
||||
result[usernames[i]].QueueSize = int(n)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Les 3 COUNT(*) par livreur (total / terminées / en cours) deviennent
|
||||
// une seule requête groupée par livreur_assign pour tous à la fois.
|
||||
type countRow struct {
|
||||
Livreur string `gorm:"column:livreur_assign"`
|
||||
Total int `gorm:"column:total"`
|
||||
Completed int `gorm:"column:completed"`
|
||||
Pending int `gorm:"column:pending"`
|
||||
}
|
||||
var rows []countRow
|
||||
err := d.GDB.Raw(`
|
||||
SELECT livreur_assign,
|
||||
COUNT(*) AS total,
|
||||
COUNT(*) FILTER (WHERE status = 'approved') AS completed,
|
||||
COUNT(*) FILTER (WHERE status IN ('assigned', 'en_route', 'livre')) AS pending
|
||||
FROM commandes
|
||||
WHERE livreur_assign IN ?
|
||||
GROUP BY livreur_assign`, usernames,
|
||||
).Scan(&rows).Error
|
||||
if err != nil {
|
||||
log.Printf("❌ [GetDeliveryPersonsDetailsBatch] Erreur comptage: %v", err)
|
||||
} else {
|
||||
for _, r := range rows {
|
||||
if det, ok := result[r.Livreur]; ok {
|
||||
det.TotalDeliveries = r.Total
|
||||
det.CompletedDeliveries = r.Completed
|
||||
det.PendingDeliveries = r.Pending
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
// GetLastDeliveryDate récupère la date de la dernière livraison d'un livreur
|
||||
func (d *Database) GetLastDeliveryDate(livreurUsername string) (*time.Time, error) {
|
||||
var result struct {
|
||||
|
||||
@@ -538,6 +538,8 @@ func (db *Database) createTables() error {
|
||||
`CREATE INDEX IF NOT EXISTS idx_jwt_date_fin ON jwt_tokens(date_fin);`,
|
||||
`CREATE INDEX IF NOT EXISTS idx_clients_telephone ON clients(telephone);`,
|
||||
`CREATE INDEX IF NOT EXISTS idx_clients_cancellations ON clients(cancellations_count);`,
|
||||
`CREATE INDEX IF NOT EXISTS idx_clients_created_at ON clients(created_at DESC);`,
|
||||
`CREATE INDEX IF NOT EXISTS idx_users_created_at ON users(created_at DESC);`,
|
||||
`CREATE INDEX IF NOT EXISTS idx_clients_amende ON clients(amende) WHERE amende > 0;`,
|
||||
`CREATE INDEX IF NOT EXISTS idx_cmd_username ON commandes(username);`,
|
||||
`CREATE INDEX IF NOT EXISTS idx_cmd_status ON commandes(status);`,
|
||||
|
||||
@@ -13,12 +13,16 @@ func (d *Database) CreateUser(user *models.User) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *Database) GetAllUsers() ([]*models.User, error) {
|
||||
func (d *Database) GetAllUsers(limit, offset int) ([]*models.User, int64, error) {
|
||||
var users []*models.User
|
||||
if err := d.GDB.Order("created_at DESC").Limit(500).Find(&users).Error; err != nil {
|
||||
return nil, fmt.Errorf("erreur lors de la récupération des utilisateurs: %w", err)
|
||||
if err := d.GDB.Order("created_at DESC").Limit(limit).Offset(offset).Find(&users).Error; err != nil {
|
||||
return nil, 0, fmt.Errorf("erreur lors de la récupération des utilisateurs: %w", err)
|
||||
}
|
||||
return users, nil
|
||||
var total int64
|
||||
if err := d.GDB.Model(&models.User{}).Count(&total).Error; err != nil {
|
||||
return nil, 0, fmt.Errorf("erreur lors du comptage des utilisateurs: %w", err)
|
||||
}
|
||||
return users, total, nil
|
||||
}
|
||||
|
||||
func (d *Database) GetAllDeliveryMen() ([]*models.User, error) {
|
||||
|
||||
@@ -511,7 +511,21 @@ func GetAllUsers(c *gin.Context) {
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "Accès réservé aux livreurs et aux administrateurs"})
|
||||
return
|
||||
}
|
||||
users, err := database.GetAllUsers()
|
||||
|
||||
limit := 100
|
||||
offset := 0
|
||||
if limitStr := c.Query("limit"); limitStr != "" {
|
||||
if l, err := strconv.Atoi(limitStr); err == nil && l > 0 && l <= 100 {
|
||||
limit = l
|
||||
}
|
||||
}
|
||||
if offsetStr := c.Query("offset"); offsetStr != "" {
|
||||
if o, err := strconv.Atoi(offsetStr); err == nil && o >= 0 {
|
||||
offset = o
|
||||
}
|
||||
}
|
||||
|
||||
users, total, err := database.GetAllUsers(limit, offset)
|
||||
|
||||
if err != nil {
|
||||
log.Printf("❌ [GET_ALL_USERS] Erreur: %v", err)
|
||||
@@ -528,11 +542,12 @@ func GetAllUsers(c *gin.Context) {
|
||||
})
|
||||
}
|
||||
|
||||
log.Printf("✅ [GET_ALL_USERS] %d users récupérés", len(sanitized))
|
||||
log.Printf("✅ [GET_ALL_USERS] %d users récupérés (offset=%d, total=%d)", len(sanitized), offset, total)
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"users": sanitized,
|
||||
"count": len(sanitized),
|
||||
"users": sanitized,
|
||||
"count": total,
|
||||
"has_more": int64(offset+len(users)) < total,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -549,13 +564,39 @@ func GetAllDeliveryMen(c *gin.Context) {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "Erreur récupération"})
|
||||
return
|
||||
}
|
||||
usernames := make([]string, len(users))
|
||||
for i, u := range users {
|
||||
usernames[i] = u.Username
|
||||
}
|
||||
detailsByUsername := database.GetDeliveryPersonsDetailsBatch(usernames)
|
||||
|
||||
var sanitized []gin.H
|
||||
for _, u := range users {
|
||||
sanitized = append(sanitized, gin.H{
|
||||
"id": u.ID,
|
||||
"username": u.Username,
|
||||
"role": u.Role,
|
||||
})
|
||||
det := detailsByUsername[u.Username]
|
||||
if det == nil {
|
||||
det = &db.DeliveryPersonDetails{Status: "offline"}
|
||||
}
|
||||
entry := gin.H{
|
||||
"id": u.ID,
|
||||
"username": u.Username,
|
||||
"role": u.Role,
|
||||
"status": det.Status,
|
||||
"queue_size": det.QueueSize,
|
||||
"total_deliveries": det.TotalDeliveries,
|
||||
"completed_deliveries": det.CompletedDeliveries,
|
||||
"pending_deliveries": det.PendingDeliveries,
|
||||
}
|
||||
if det.CurrentCommand != 0 {
|
||||
entry["current_command"] = det.CurrentCommand
|
||||
} else {
|
||||
entry["current_command"] = nil
|
||||
}
|
||||
if det.HasLocation {
|
||||
entry["location"] = gin.H{"latitude": det.Latitude, "longitude": det.Longitude}
|
||||
} else {
|
||||
entry["location"] = nil
|
||||
}
|
||||
sanitized = append(sanitized, entry)
|
||||
}
|
||||
|
||||
log.Printf("✅ [GET_ALL_USERS] %d users récupérés", len(sanitized))
|
||||
@@ -575,16 +616,33 @@ func GetAllClients(c *gin.Context) {
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "Accès réservé aux livreurs et aux administrateurs"})
|
||||
return
|
||||
}
|
||||
clients, err := database.GetAllClients()
|
||||
|
||||
limit := 100
|
||||
offset := 0
|
||||
if limitStr := c.Query("limit"); limitStr != "" {
|
||||
if l, err := strconv.Atoi(limitStr); err == nil && l > 0 && l <= 100 {
|
||||
limit = l
|
||||
}
|
||||
}
|
||||
if offsetStr := c.Query("offset"); offsetStr != "" {
|
||||
if o, err := strconv.Atoi(offsetStr); err == nil && o >= 0 {
|
||||
offset = o
|
||||
}
|
||||
}
|
||||
|
||||
clients, total, err := database.GetAllClients(limit, offset)
|
||||
if err != nil {
|
||||
log.Printf("❌ [GET_ALL_CLIENTS] Erreur: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "Erreur récupération"})
|
||||
return
|
||||
}
|
||||
|
||||
limited := rateLimitedClients(clients)
|
||||
|
||||
var sanitized []gin.H
|
||||
for _, cl := range clients {
|
||||
sanitized = append(sanitized, gin.H{
|
||||
"rate_limited": limited[cl.Username],
|
||||
"id": cl.ID,
|
||||
"username": cl.Username,
|
||||
"nom": cl.Nom,
|
||||
@@ -596,14 +654,16 @@ func GetAllClients(c *gin.Context) {
|
||||
"cancellations_count": cl.CancellationsCount,
|
||||
"last_penalty_reason": cl.LastPenaltyReason,
|
||||
"referral_balance": cl.ReferralBalance,
|
||||
"parrain": cl.Parrain,
|
||||
})
|
||||
}
|
||||
|
||||
log.Printf("✅ [GET_ALL_CLIENTS] %d clients récupérés", len(sanitized))
|
||||
log.Printf("✅ [GET_ALL_CLIENTS] %d clients récupérés (offset=%d, total=%d)", len(sanitized), offset, total)
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"clients": sanitized,
|
||||
"count": len(sanitized),
|
||||
"clients": sanitized,
|
||||
"count": total,
|
||||
"has_more": int64(offset+len(clients)) < total,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
@@ -14,11 +15,26 @@ import (
|
||||
|
||||
var (
|
||||
cancelRateLimitMap = make(map[string][]time.Time)
|
||||
cancelRateLimitMu sync.Mutex
|
||||
cancelMaxRequests = 5 // Max 5 annulations
|
||||
cancelTimeWindow = time.Hour // Par heure
|
||||
)
|
||||
|
||||
func isCancelRateLimited(key string) bool {
|
||||
cancelRateLimitMu.Lock()
|
||||
defer cancelRateLimitMu.Unlock()
|
||||
return countRecent(cancelRateLimitMap[key], cancelTimeWindow) >= cancelMaxRequests
|
||||
}
|
||||
|
||||
func resetCancelRateLimit(key string) {
|
||||
cancelRateLimitMu.Lock()
|
||||
defer cancelRateLimitMu.Unlock()
|
||||
delete(cancelRateLimitMap, key)
|
||||
}
|
||||
|
||||
func checkCancelRateLimit(key string) bool {
|
||||
cancelRateLimitMu.Lock()
|
||||
defer cancelRateLimitMu.Unlock()
|
||||
now := time.Now()
|
||||
|
||||
if timestamps, exists := cancelRateLimitMap[key]; exists {
|
||||
@@ -67,7 +83,7 @@ func CancelCommandByClient(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
rateLimitKey := fmt.Sprintf("cancel:%s", username)
|
||||
rateLimitKey := cancelRateLimitKey(username)
|
||||
if !checkCancelRateLimit(rateLimitKey) {
|
||||
log.Printf("⚠️ [CANCEL_CLIENT] Rate limit dépassé pour %s", username)
|
||||
c.JSON(http.StatusTooManyRequests, gin.H{
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"gestion/db"
|
||||
"gestion/middleware"
|
||||
"gestion/models"
|
||||
"gestion/utils"
|
||||
"log"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func cancelRateLimitKey(username string) string {
|
||||
return "cancel:" + username
|
||||
}
|
||||
|
||||
func ownAddressRateLimitKey(username string) string {
|
||||
return "update_own_addr:" + username
|
||||
}
|
||||
|
||||
// rateLimitedClients renvoie les usernames actuellement bloqués par l'un des
|
||||
// rate limits client : requêtes panier/commande (Redis), annulations et
|
||||
// modification d'adresse (mémoire). Un seul MGET pour toute la liste.
|
||||
func rateLimitedClients(clients []*models.Client) map[string]bool {
|
||||
limited := make(map[string]bool)
|
||||
if len(clients) == 0 {
|
||||
return limited
|
||||
}
|
||||
|
||||
keys := make([]string, len(clients))
|
||||
for i, cl := range clients {
|
||||
keys[i] = middleware.ClientRateLimitKey(cl.ID)
|
||||
}
|
||||
counts, err := db.Redis.MGet(db.RedisCtx, keys...).Result()
|
||||
if err != nil {
|
||||
log.Printf("⚠️ [RATELIMIT_STATUS] Erreur Redis: %v", err)
|
||||
}
|
||||
for i, v := range counts {
|
||||
s, ok := v.(string)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if n, err := strconv.Atoi(s); err == nil && n > middleware.ClientRateLimitMax {
|
||||
limited[clients[i].Username] = true
|
||||
}
|
||||
}
|
||||
|
||||
for _, cl := range clients {
|
||||
if isCancelRateLimited(cancelRateLimitKey(cl.Username)) || isRateLimited(ownAddressRateLimitKey(cl.Username)) {
|
||||
limited[cl.Username] = true
|
||||
}
|
||||
}
|
||||
return limited
|
||||
}
|
||||
|
||||
// ResetClientRateLimitAdmin lève tous les rate limits d'un client.
|
||||
// POST /api/v2/admin/protected/client/:username/ratelimit/reset
|
||||
func ResetClientRateLimitAdmin(c *gin.Context) {
|
||||
if c.GetString("role") != "admin" {
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "Accès réservé aux administrateurs"})
|
||||
return
|
||||
}
|
||||
|
||||
database := c.MustGet("database").(*db.Database)
|
||||
client, err := database.GetClientByUsername(c.Param("username"))
|
||||
if err != nil || client == nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "Client introuvable"})
|
||||
return
|
||||
}
|
||||
|
||||
if err := db.Redis.Del(db.RedisCtx, middleware.ClientRateLimitKey(client.ID)).Err(); err != nil {
|
||||
utils.ServerErr(c, "Erreur levée du rate limit", err)
|
||||
return
|
||||
}
|
||||
resetCancelRateLimit(cancelRateLimitKey(client.Username))
|
||||
resetRateLimit(ownAddressRateLimitKey(client.Username))
|
||||
|
||||
log.Printf("✅ [RATELIMIT_RESET] Rate limit levé pour %s par %s", client.Username, c.GetString("username"))
|
||||
c.JSON(http.StatusOK, gin.H{"success": true, "message": "Rate limit levé"})
|
||||
}
|
||||
@@ -48,6 +48,30 @@ func checkRateLimit(key string) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// isRateLimited indique si la clé est actuellement bloquée, sans compter de requête.
|
||||
func isRateLimited(key string) bool {
|
||||
rateLimitMu.Lock()
|
||||
defer rateLimitMu.Unlock()
|
||||
return countRecent(rateLimitMap[key], timeWindow) >= maxRequests
|
||||
}
|
||||
|
||||
func resetRateLimit(key string) {
|
||||
rateLimitMu.Lock()
|
||||
defer rateLimitMu.Unlock()
|
||||
delete(rateLimitMap, key)
|
||||
}
|
||||
|
||||
func countRecent(timestamps []time.Time, window time.Duration) int {
|
||||
now := time.Now()
|
||||
n := 0
|
||||
for _, ts := range timestamps {
|
||||
if now.Sub(ts) < window {
|
||||
n++
|
||||
}
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func safeGetUsername(c *gin.Context) (string, error) {
|
||||
username, exists := c.Get("username")
|
||||
if !exists {
|
||||
@@ -356,7 +380,7 @@ func UpdateOwnCommandAddress(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
rateLimitKey := fmt.Sprintf("update_own_addr:%s", clientUsername)
|
||||
rateLimitKey := ownAddressRateLimitKey(clientUsername)
|
||||
if !checkRateLimit(rateLimitKey) {
|
||||
c.JSON(http.StatusTooManyRequests, gin.H{"error": "Trop de requêtes, réessayez plus tard"})
|
||||
return
|
||||
@@ -746,6 +770,39 @@ func GetAvailableDeliveryPersons(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
// Enrichissement en un seul aller-retour groupé (statut, position, queue,
|
||||
// compteurs) au lieu de laisser le frontend refaire un appel par livreur.
|
||||
usernames := make([]string, len(livreurs))
|
||||
for i, l := range livreurs {
|
||||
if u, ok := l["username"].(string); ok {
|
||||
usernames[i] = u
|
||||
}
|
||||
}
|
||||
detailsByUsername := database.GetDeliveryPersonsDetailsBatch(usernames)
|
||||
for i, l := range livreurs {
|
||||
username, _ := l["username"].(string)
|
||||
det := detailsByUsername[username]
|
||||
if det == nil {
|
||||
det = &db.DeliveryPersonDetails{Status: "offline"}
|
||||
}
|
||||
l["status"] = det.Status
|
||||
l["queue_size"] = det.QueueSize
|
||||
l["total_deliveries"] = det.TotalDeliveries
|
||||
l["completed_deliveries"] = det.CompletedDeliveries
|
||||
l["pending_deliveries"] = det.PendingDeliveries
|
||||
if det.CurrentCommand != 0 {
|
||||
l["current_command"] = det.CurrentCommand
|
||||
} else {
|
||||
l["current_command"] = nil
|
||||
}
|
||||
if det.HasLocation {
|
||||
l["location"] = gin.H{"latitude": det.Latitude, "longitude": det.Longitude}
|
||||
} else {
|
||||
l["location"] = nil
|
||||
}
|
||||
livreurs[i] = l
|
||||
}
|
||||
|
||||
log.Printf("✅ [GET_LIVREURS] Trouvés: %d livreurs disponibles", len(livreurs))
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
|
||||
@@ -437,6 +437,13 @@ func ClientSessionMiddleware(c *gin.Context) {
|
||||
c.Next()
|
||||
}
|
||||
|
||||
// ClientRateLimitMax est le nombre de requêtes autorisées par minute et par client.
|
||||
const ClientRateLimitMax = 100
|
||||
|
||||
func ClientRateLimitKey(clientID int) string {
|
||||
return "ratelimit:" + strconv.Itoa(clientID)
|
||||
}
|
||||
|
||||
func RateLimitMiddleware(c *gin.Context) {
|
||||
// Récupérer le client_id
|
||||
clientID, ok := c.Get("client_id")
|
||||
@@ -446,7 +453,7 @@ func RateLimitMiddleware(c *gin.Context) {
|
||||
}
|
||||
|
||||
clientIDInt := clientID.(int)
|
||||
rateLimitKey := "ratelimit:" + strconv.Itoa(clientIDInt)
|
||||
rateLimitKey := ClientRateLimitKey(clientIDInt)
|
||||
|
||||
// Incrémenter le compteur
|
||||
count, err := db.Redis.Incr(db.RedisCtx, rateLimitKey).Result()
|
||||
@@ -460,7 +467,7 @@ func RateLimitMiddleware(c *gin.Context) {
|
||||
db.Redis.Expire(db.RedisCtx, rateLimitKey, 60*time.Second) // 1 minute
|
||||
}
|
||||
|
||||
if count > 100 {
|
||||
if count > ClientRateLimitMax {
|
||||
log.Printf("❌ [RATELIMIT] Client %d dépassé le limite: %d requêtes/min", clientIDInt, count)
|
||||
c.JSON(http.StatusTooManyRequests, gin.H{
|
||||
"error": "Trop de requêtes - Réessayez dans une minute",
|
||||
@@ -469,9 +476,9 @@ func RateLimitMiddleware(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
c.Header("X-RateLimit-Remaining", strconv.FormatInt(100-count, 10))
|
||||
c.Header("X-RateLimit-Remaining", strconv.FormatInt(ClientRateLimitMax-count, 10))
|
||||
|
||||
log.Printf("📊 [RATELIMIT] Client %d: %d/%d requêtes", clientIDInt, count, 100)
|
||||
log.Printf("📊 [RATELIMIT] Client %d: %d/%d requêtes", clientIDInt, count, ClientRateLimitMax)
|
||||
|
||||
c.Next()
|
||||
}
|
||||
|
||||
@@ -293,6 +293,7 @@ func SetupRoutes(router *gin.Engine, database *db.Database, geoService *services
|
||||
adminGroupV2.POST("/client/:username/points/add", handlers.AddClientPointsAdmin) // Ajouter points par pool
|
||||
adminGroupV2.POST("/client/:username/points/subtract", handlers.SubtractClientPointsAdmin) // Enlever points par pool
|
||||
adminGroupV2.POST("/client/:username/rewards/reset", handlers.AdminResetClientRedeemed) // Reset récompenses réclamées
|
||||
adminGroupV2.POST("/client/:username/ratelimit/reset", handlers.ResetClientRateLimitAdmin) // Lever les rate limits
|
||||
adminGroupV2.GET("/penalties/all", handlers.GetAllClientsWithPenalties) // Liste clients avec pénalités
|
||||
adminGroupV2.GET("/penalties/stats", handlers.GetPenaltiesStats)
|
||||
|
||||
|
||||
@@ -0,0 +1,244 @@
|
||||
// Tests du statut "rate_limited" exposé par GET /all/clients et de la levée
|
||||
// des rate limits par un admin (POST /client/:username/ratelimit/reset).
|
||||
// Couvre les trois limites client : requêtes panier/commande (Redis),
|
||||
// annulations et modification d'adresse (mémoire).
|
||||
package tests
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"gestion/db"
|
||||
"gestion/handlers"
|
||||
"gestion/middleware"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func clientID(t *testing.T, username string) int {
|
||||
t.Helper()
|
||||
cl, err := testDB.GetClientByUsername(username)
|
||||
if err != nil || cl == nil {
|
||||
t.Fatalf("client %q introuvable: %v", username, err)
|
||||
}
|
||||
return cl.ID
|
||||
}
|
||||
|
||||
func setRequestCount(t *testing.T, username string, count int) {
|
||||
t.Helper()
|
||||
key := middleware.ClientRateLimitKey(clientID(t, username))
|
||||
if err := db.Redis.Set(db.RedisCtx, key, count, 0).Err(); err != nil {
|
||||
t.Fatalf("set compteur redis: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { db.Redis.Del(db.RedisCtx, key) })
|
||||
}
|
||||
|
||||
// rateLimitedStatus renvoie le champ rate_limited de chaque client de la
|
||||
// première page de GET /all/clients.
|
||||
func rateLimitedStatus(t *testing.T) map[string]bool {
|
||||
t.Helper()
|
||||
c, rec := clientsListContext("admin", url.Values{})
|
||||
handlers.GetAllClients(c)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("GetAllClients: got=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var resp struct {
|
||||
Clients []struct {
|
||||
Username string `json:"username"`
|
||||
RateLimited bool `json:"rate_limited"`
|
||||
} `json:"clients"`
|
||||
}
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
|
||||
t.Fatalf("décodage réponse: %v", err)
|
||||
}
|
||||
status := make(map[string]bool, len(resp.Clients))
|
||||
for _, cl := range resp.Clients {
|
||||
status[cl.Username] = cl.RateLimited
|
||||
}
|
||||
return status
|
||||
}
|
||||
|
||||
func resetRateLimit(t *testing.T, role, username string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/api/v2/admin/protected/client/"+username+"/ratelimit/reset", nil)
|
||||
c.Set("database", testDB)
|
||||
c.Set("role", role)
|
||||
c.Set("username", testUserPrefix+"rl_admin")
|
||||
c.Params = gin.Params{{Key: "username", Value: username}}
|
||||
handlers.ResetClientRateLimitAdmin(c)
|
||||
return rec
|
||||
}
|
||||
|
||||
func clientContext(username, method, path string, body string) (*gin.Context, *httptest.ResponseRecorder) {
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
c.Request = httptest.NewRequest(method, path, strings.NewReader(body))
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
c.Set("database", testDB)
|
||||
c.Set("geoService", ensureTestGeoService())
|
||||
c.Set("role", "client")
|
||||
c.Set("username", username)
|
||||
// id=0 est rejeté après le contrôle du rate limit : chaque appel compte
|
||||
// une tentative sans toucher à une vraie commande.
|
||||
c.Params = gin.Params{{Key: "id", Value: "0"}}
|
||||
return c, rec
|
||||
}
|
||||
|
||||
func cancelAttempt(username string) int {
|
||||
c, rec := clientContext(username, http.MethodPost, "/api/v1/commands/0/cancel", `{}`)
|
||||
handlers.CancelCommandByClient(c)
|
||||
return rec.Code
|
||||
}
|
||||
|
||||
func addressAttempt(username string) int {
|
||||
c, rec := clientContext(username, http.MethodPut, "/api/v1/commands/0/address", `{"delivery_address":"1 rue test"}`)
|
||||
handlers.UpdateOwnCommandAddress(c)
|
||||
return rec.Code
|
||||
}
|
||||
|
||||
// ── Statut rate_limited (Redis) ────────────────────────────────────────────
|
||||
|
||||
func TestGetAllClients_RateLimitedReflectsRequestCounter(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
blocked := newTestClient(t, "rl_blocked")
|
||||
atLimit := newTestClient(t, "rl_at_limit")
|
||||
free := newTestClient(t, "rl_free")
|
||||
|
||||
setRequestCount(t, blocked, middleware.ClientRateLimitMax+1)
|
||||
// Le middleware ne bloque qu'au-delà du max : pile au max, la requête passe encore.
|
||||
setRequestCount(t, atLimit, middleware.ClientRateLimitMax)
|
||||
|
||||
status := rateLimitedStatus(t)
|
||||
if !status[blocked] {
|
||||
t.Errorf("%s (compteur > max) doit être rate_limited", blocked)
|
||||
}
|
||||
if status[atLimit] {
|
||||
t.Errorf("%s (compteur = max) ne doit pas être rate_limited", atLimit)
|
||||
}
|
||||
if status[free] {
|
||||
t.Errorf("%s (aucun compteur) ne doit pas être rate_limited", free)
|
||||
}
|
||||
}
|
||||
|
||||
// ── Levée du rate limit ─────────────────────────────────────────────────────
|
||||
|
||||
func TestResetClientRateLimit_ClearsRequestCounter(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
username := newTestClient(t, "rl_reset_redis")
|
||||
setRequestCount(t, username, middleware.ClientRateLimitMax+50)
|
||||
|
||||
if rec := resetRateLimit(t, "admin", username); rec.Code != http.StatusOK {
|
||||
t.Fatalf("reset: got=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
key := middleware.ClientRateLimitKey(clientID(t, username))
|
||||
if n, _ := db.Redis.Exists(db.RedisCtx, key).Result(); n != 0 {
|
||||
t.Errorf("le compteur Redis doit être supprimé après le reset")
|
||||
}
|
||||
if rateLimitedStatus(t)[username] {
|
||||
t.Errorf("%s ne doit plus être rate_limited après le reset", username)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResetClientRateLimit_ClearsCancelLimit(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
username := newTestClient(t, "rl_reset_cancel")
|
||||
t.Cleanup(func() { resetRateLimit(t, "admin", username) })
|
||||
|
||||
for i := 0; i < 5; i++ {
|
||||
cancelAttempt(username)
|
||||
}
|
||||
if code := cancelAttempt(username); code != http.StatusTooManyRequests {
|
||||
t.Fatalf("6e annulation doit être bloquée: got=%d want=429", code)
|
||||
}
|
||||
if !rateLimitedStatus(t)[username] {
|
||||
t.Fatalf("%s bloqué sur les annulations doit être rate_limited", username)
|
||||
}
|
||||
|
||||
if rec := resetRateLimit(t, "admin", username); rec.Code != http.StatusOK {
|
||||
t.Fatalf("reset: got=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
if rateLimitedStatus(t)[username] {
|
||||
t.Errorf("%s ne doit plus être rate_limited après le reset", username)
|
||||
}
|
||||
if code := cancelAttempt(username); code == http.StatusTooManyRequests {
|
||||
t.Errorf("après le reset, l'annulation ne doit plus être bloquée par le rate limit")
|
||||
}
|
||||
}
|
||||
|
||||
func TestResetClientRateLimit_ClearsAddressLimit(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
username := newTestClient(t, "rl_reset_addr")
|
||||
t.Cleanup(func() { resetRateLimit(t, "admin", username) })
|
||||
|
||||
for i := 0; i < 10; i++ {
|
||||
addressAttempt(username)
|
||||
}
|
||||
if code := addressAttempt(username); code != http.StatusTooManyRequests {
|
||||
t.Fatalf("11e modification d'adresse doit être bloquée: got=%d want=429", code)
|
||||
}
|
||||
if !rateLimitedStatus(t)[username] {
|
||||
t.Fatalf("%s bloqué sur les modifications d'adresse doit être rate_limited", username)
|
||||
}
|
||||
|
||||
if rec := resetRateLimit(t, "admin", username); rec.Code != http.StatusOK {
|
||||
t.Fatalf("reset: got=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
if rateLimitedStatus(t)[username] {
|
||||
t.Errorf("%s ne doit plus être rate_limited après le reset", username)
|
||||
}
|
||||
if code := addressAttempt(username); code == http.StatusTooManyRequests {
|
||||
t.Errorf("après le reset, la modification d'adresse ne doit plus être bloquée par le rate limit")
|
||||
}
|
||||
}
|
||||
|
||||
// Le reset d'un client ne doit pas débloquer les autres.
|
||||
func TestResetClientRateLimit_OnlyAffectsTargetClient(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
target := newTestClient(t, "rl_target")
|
||||
other := newTestClient(t, "rl_other")
|
||||
setRequestCount(t, target, middleware.ClientRateLimitMax+1)
|
||||
setRequestCount(t, other, middleware.ClientRateLimitMax+1)
|
||||
|
||||
if rec := resetRateLimit(t, "admin", target); rec.Code != http.StatusOK {
|
||||
t.Fatalf("reset: got=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
status := rateLimitedStatus(t)
|
||||
if status[target] {
|
||||
t.Errorf("%s doit être débloqué", target)
|
||||
}
|
||||
if !status[other] {
|
||||
t.Errorf("%s ne doit pas être affecté par le reset d'un autre client", other)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResetClientRateLimit_RejectsNonAdmin(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
username := newTestClient(t, "rl_forbidden")
|
||||
setRequestCount(t, username, middleware.ClientRateLimitMax+1)
|
||||
|
||||
for _, role := range []string{"cabine", "livreur", "client"} {
|
||||
if rec := resetRateLimit(t, role, username); rec.Code != http.StatusForbidden {
|
||||
t.Errorf("role %s doit être refusé: got=%d want=403", role, rec.Code)
|
||||
}
|
||||
}
|
||||
if !rateLimitedStatus(t)[username] {
|
||||
t.Errorf("un reset refusé ne doit pas débloquer le client")
|
||||
}
|
||||
}
|
||||
|
||||
func TestResetClientRateLimit_UnknownClientReturns404(t *testing.T) {
|
||||
rec := resetRateLimit(t, "admin", testUserPrefix+"rl_does_not_exist")
|
||||
if rec.Code != http.StatusNotFound {
|
||||
t.Errorf("client inconnu: got=%d want=404", rec.Code)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,289 @@
|
||||
// Tests pour GetDeliveryPersonsDetailsBatch, qui remplace l'ancien pattern
|
||||
// N+1 (une requête complète par livreur : GetUserByUsername + 2 lectures
|
||||
// Redis + GetDeliverymanQueueSize + GetCurrentCommand + 3 COUNT(*) séparés)
|
||||
// par un enrichissement groupé de toute la liste en un seul appel. On
|
||||
// vérifie que le résultat groupé est strictement équivalent à ce que
|
||||
// renvoyaient les anciennes fonctions individuelles, livreur par livreur.
|
||||
package tests
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"gestion/db"
|
||||
"gestion/handlers"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func setDeliveryStatus(t *testing.T, username, status string) {
|
||||
t.Helper()
|
||||
key := fmt.Sprintf("delivery:status:%s", username)
|
||||
if err := db.Redis.Set(db.RedisCtx, key, status, 0).Err(); err != nil {
|
||||
t.Fatalf("set status redis %q: %v", username, err)
|
||||
}
|
||||
t.Cleanup(func() { db.Redis.Del(db.RedisCtx, key) })
|
||||
}
|
||||
|
||||
func setDeliveryLocation(t *testing.T, username string, lat, lon float64, lastUpdate int64) {
|
||||
t.Helper()
|
||||
key := fmt.Sprintf("delivery:location:%s", username)
|
||||
payload, _ := json.Marshal(map[string]any{
|
||||
"latitude": lat,
|
||||
"longitude": lon,
|
||||
"last_update": lastUpdate,
|
||||
})
|
||||
if err := db.Redis.Set(db.RedisCtx, key, payload, 0).Err(); err != nil {
|
||||
t.Fatalf("set location redis %q: %v", username, err)
|
||||
}
|
||||
t.Cleanup(func() { db.Redis.Del(db.RedisCtx, key) })
|
||||
}
|
||||
|
||||
func pushDeliveryQueue(t *testing.T, username string, commandIDs ...int) {
|
||||
t.Helper()
|
||||
key := fmt.Sprintf("delivery:queue:%s", username)
|
||||
for _, id := range commandIDs {
|
||||
if err := db.Redis.RPush(db.RedisCtx, key, fmt.Sprintf("%d", id)).Err(); err != nil {
|
||||
t.Fatalf("rpush queue redis %q: %v", username, err)
|
||||
}
|
||||
}
|
||||
t.Cleanup(func() { db.Redis.Del(db.RedisCtx, key) })
|
||||
}
|
||||
|
||||
func setDeliveryCurrentCommand(t *testing.T, username string, commandID int) {
|
||||
t.Helper()
|
||||
key := fmt.Sprintf("delivery:current:%s", username)
|
||||
if err := db.Redis.Set(db.RedisCtx, key, fmt.Sprintf("%d", commandID), 0).Err(); err != nil {
|
||||
t.Fatalf("set current command redis %q: %v", username, err)
|
||||
}
|
||||
t.Cleanup(func() { db.Redis.Del(db.RedisCtx, key) })
|
||||
}
|
||||
|
||||
// Livreur avec statut, position, queue, commande en cours et un historique
|
||||
// de commandes mixte (approved / en_route / pending) : couvre tous les
|
||||
// champs enrichis par le batch en une seule fois.
|
||||
func TestGetDeliveryPersonsDetailsBatch_FullyPopulatedLivreur(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
livreur := newTestLivreur(t, "batch_full")
|
||||
client := newTestClient(t, "batch_full_client")
|
||||
productID := newTestProduct(t, "BatchFull", 100)
|
||||
|
||||
newTestCommandWithItem(t, client, "approved", livreur, productID, 1, 10)
|
||||
newTestCommandWithItem(t, client, "en_route", livreur, productID, 1, 10)
|
||||
newTestCommandWithItem(t, client, "pending", livreur, productID, 1, 10)
|
||||
|
||||
setDeliveryStatus(t, livreur, "available")
|
||||
setDeliveryLocation(t, livreur, 47.21, -1.55, 1700000000)
|
||||
pushDeliveryQueue(t, livreur, 101, 102)
|
||||
setDeliveryCurrentCommand(t, livreur, 101)
|
||||
|
||||
result := testDB.GetDeliveryPersonsDetailsBatch([]string{livreur})
|
||||
det, ok := result[livreur]
|
||||
if !ok || det == nil {
|
||||
t.Fatalf("GetDeliveryPersonsDetailsBatch doit renvoyer une entrée pour %q", livreur)
|
||||
}
|
||||
|
||||
if det.Status != "available" {
|
||||
t.Errorf("Status: got=%q want=%q", det.Status, "available")
|
||||
}
|
||||
if !det.HasLocation || det.Latitude != 47.21 || det.Longitude != -1.55 {
|
||||
t.Errorf("Location: got=(hasLoc=%v, %f, %f) want=(true, 47.21, -1.55)", det.HasLocation, det.Latitude, det.Longitude)
|
||||
}
|
||||
if det.QueueSize != 2 {
|
||||
t.Errorf("QueueSize: got=%d want=2", det.QueueSize)
|
||||
}
|
||||
if det.CurrentCommand != 101 {
|
||||
t.Errorf("CurrentCommand: got=%d want=101", det.CurrentCommand)
|
||||
}
|
||||
// total = toutes statuts confondus ; completed = 'approved' uniquement ;
|
||||
// pending = assigned/en_route/livre (donc PAS le statut littéral "pending").
|
||||
if det.TotalDeliveries != 3 {
|
||||
t.Errorf("TotalDeliveries: got=%d want=3", det.TotalDeliveries)
|
||||
}
|
||||
if det.CompletedDeliveries != 1 {
|
||||
t.Errorf("CompletedDeliveries: got=%d want=1", det.CompletedDeliveries)
|
||||
}
|
||||
if det.PendingDeliveries != 1 {
|
||||
t.Errorf("PendingDeliveries (assigned/en_route/livre): got=%d want=1", det.PendingDeliveries)
|
||||
}
|
||||
}
|
||||
|
||||
// Un livreur sans aucune donnée Redis/commande doit retomber sur les mêmes
|
||||
// valeurs par défaut que les anciennes fonctions individuelles (offline,
|
||||
// pas de position, compteurs à 0) plutôt que de planter ou de renvoyer du
|
||||
// bruit.
|
||||
func TestGetDeliveryPersonsDetailsBatch_LivreurWithoutAnyData(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
livreur := newTestLivreur(t, "batch_empty")
|
||||
|
||||
result := testDB.GetDeliveryPersonsDetailsBatch([]string{livreur})
|
||||
det, ok := result[livreur]
|
||||
if !ok || det == nil {
|
||||
t.Fatalf("GetDeliveryPersonsDetailsBatch doit renvoyer une entrée pour %q même sans données", livreur)
|
||||
}
|
||||
if det.Status != "offline" {
|
||||
t.Errorf("Status par défaut: got=%q want=%q", det.Status, "offline")
|
||||
}
|
||||
if det.HasLocation {
|
||||
t.Errorf("HasLocation doit être false sans position enregistrée")
|
||||
}
|
||||
if det.QueueSize != 0 || det.CurrentCommand != 0 {
|
||||
t.Errorf("queue/commande courante doivent être à 0: queue=%d current=%d", det.QueueSize, det.CurrentCommand)
|
||||
}
|
||||
if det.TotalDeliveries != 0 || det.CompletedDeliveries != 0 || det.PendingDeliveries != 0 {
|
||||
t.Errorf("compteurs doivent être à 0 sans commande: total=%d completed=%d pending=%d",
|
||||
det.TotalDeliveries, det.CompletedDeliveries, det.PendingDeliveries)
|
||||
}
|
||||
}
|
||||
|
||||
// Les commandes d'un livreur ne doivent jamais fuiter dans les compteurs
|
||||
// d'un autre : le GROUP BY livreur_assign du batch doit bien isoler chaque
|
||||
// livreur, comme le faisait un CountDeliveriesByStatus(username, ...) par
|
||||
// livreur auparavant.
|
||||
func TestGetDeliveryPersonsDetailsBatch_IsolatesCountsPerLivreur(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
livreurA := newTestLivreur(t, "batch_iso_a")
|
||||
livreurB := newTestLivreur(t, "batch_iso_b")
|
||||
client := newTestClient(t, "batch_iso_client")
|
||||
productID := newTestProduct(t, "BatchIso", 100)
|
||||
|
||||
newTestCommandWithItem(t, client, "approved", livreurA, productID, 1, 10)
|
||||
newTestCommandWithItem(t, client, "approved", livreurB, productID, 1, 10)
|
||||
newTestCommandWithItem(t, client, "approved", livreurB, productID, 1, 10)
|
||||
|
||||
result := testDB.GetDeliveryPersonsDetailsBatch([]string{livreurA, livreurB})
|
||||
if result[livreurA].TotalDeliveries != 1 {
|
||||
t.Errorf("livreurA: got=%d want=1", result[livreurA].TotalDeliveries)
|
||||
}
|
||||
if result[livreurB].TotalDeliveries != 2 {
|
||||
t.Errorf("livreurB: got=%d want=2", result[livreurB].TotalDeliveries)
|
||||
}
|
||||
}
|
||||
|
||||
// ── Handlers enrichis : GetAvailableDeliveryPersons (admin) ───────────────
|
||||
|
||||
func availableDeliveryPersonsContext(role string) (*gin.Context, *httptest.ResponseRecorder) {
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v2/admin/protected/delivery-persons", nil)
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
c.Request = req
|
||||
c.Set("database", testDB)
|
||||
c.Set("role", role)
|
||||
return c, rec
|
||||
}
|
||||
|
||||
type enrichedLivreurResponse struct {
|
||||
Livreurs []struct {
|
||||
Username string `json:"username"`
|
||||
Status string `json:"status"`
|
||||
QueueSize int `json:"queue_size"`
|
||||
TotalDeliveries int `json:"total_deliveries"`
|
||||
CompletedDeliveries int `json:"completed_deliveries"`
|
||||
} `json:"livreurs"`
|
||||
}
|
||||
|
||||
func TestGetAvailableDeliveryPersonsHandler_IncludesEnrichedFields(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
livreur := newTestLivreur(t, "handler_enrich_a")
|
||||
client := newTestClient(t, "handler_enrich_client")
|
||||
productID := newTestProduct(t, "HandlerEnrich", 100)
|
||||
newTestCommandWithItem(t, client, "approved", livreur, productID, 1, 10)
|
||||
setDeliveryStatus(t, livreur, "busy")
|
||||
|
||||
c, rec := availableDeliveryPersonsContext("admin")
|
||||
handlers.GetAvailableDeliveryPersons(c)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("got=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
var resp enrichedLivreurResponse
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
|
||||
t.Fatalf("décodage réponse: %v body=%s", err, rec.Body.String())
|
||||
}
|
||||
found := false
|
||||
for _, l := range resp.Livreurs {
|
||||
if l.Username != livreur {
|
||||
continue
|
||||
}
|
||||
found = true
|
||||
if l.Status != "busy" {
|
||||
t.Errorf("status: got=%q want=%q", l.Status, "busy")
|
||||
}
|
||||
if l.TotalDeliveries != 1 || l.CompletedDeliveries != 1 {
|
||||
t.Errorf("compteurs: got total=%d completed=%d want total=1 completed=1", l.TotalDeliveries, l.CompletedDeliveries)
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatalf("le livreur %q n'apparaît pas dans la réponse enrichie: body=%s", livreur, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// ── Handlers enrichis : GetAllDeliveryMen (cabine) ────────────────────────
|
||||
|
||||
func allDeliveryMenContext(role string) (*gin.Context, *httptest.ResponseRecorder) {
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/cabine/all/deliveryman", nil)
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
c.Request = req
|
||||
c.Set("database", testDB)
|
||||
c.Set("role", role)
|
||||
return c, rec
|
||||
}
|
||||
|
||||
type enrichedUsersResponse struct {
|
||||
Users []struct {
|
||||
Username string `json:"username"`
|
||||
Status string `json:"status"`
|
||||
QueueSize int `json:"queue_size"`
|
||||
} `json:"users"`
|
||||
}
|
||||
|
||||
func TestGetAllDeliveryMenHandler_IncludesEnrichedFields(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
livreur := newTestLivreur(t, "handler_enrich_b")
|
||||
pushDeliveryQueue(t, livreur, 201, 202, 203)
|
||||
|
||||
c, rec := allDeliveryMenContext("cabine")
|
||||
handlers.GetAllDeliveryMen(c)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("got=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
var resp enrichedUsersResponse
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
|
||||
t.Fatalf("décodage réponse: %v body=%s", err, rec.Body.String())
|
||||
}
|
||||
found := false
|
||||
for _, u := range resp.Users {
|
||||
if u.Username != livreur {
|
||||
continue
|
||||
}
|
||||
found = true
|
||||
if u.QueueSize != 3 {
|
||||
t.Errorf("queue_size: got=%d want=3", u.QueueSize)
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatalf("le livreur %q n'apparaît pas dans la réponse enrichie: body=%s", livreur, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// Sans livreur, aucun appel Redis/SQL ne doit partir (MGET sans clé est
|
||||
// rejeté par Redis, IN () est invalide en SQL) : on doit simplement
|
||||
// récupérer une map vide, pour une liste vide comme pour nil.
|
||||
func TestGetDeliveryPersonsDetailsBatch_EmptyInputReturnsEmptyMap(t *testing.T) {
|
||||
for name, input := range map[string][]string{"slice vide": {}, "nil": nil} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
result := testDB.GetDeliveryPersonsDetailsBatch(input)
|
||||
if result == nil {
|
||||
t.Fatal("doit renvoyer une map vide, pas nil")
|
||||
}
|
||||
if len(result) != 0 {
|
||||
t.Errorf("map attendue vide: got=%d entrées", len(result))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -37,6 +37,9 @@ func nextTestPhone() string {
|
||||
func TestMain(m *testing.M) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
testDB = db.InitDB()
|
||||
// Même séquence que main.go : sans cette migration, la colonne
|
||||
// two_fa_enabled manque et GetClientByUsername échoue.
|
||||
testDB.MigrateAddTelegramColumns()
|
||||
db.InitRedis()
|
||||
os.Exit(m.Run())
|
||||
}
|
||||
|
||||
@@ -0,0 +1,457 @@
|
||||
// Tests pour la pagination de GET /admin/protected/all/clients et
|
||||
// GET /admin/protected/all/users (db.GetAllClients / db.GetAllUsers et leurs
|
||||
// handlers), ajoutée pour éviter de charger la table entière d'un coup, et
|
||||
// pour la régression N+1 sur le champ "parrain" (désormais inclus directement
|
||||
// dans GetAllClients au lieu d'un appel séparé par client).
|
||||
//
|
||||
// Les totaux attendus sont calculés par rapport à une mesure de référence
|
||||
// (baseline) prise avant la création des données de test, pour que ces tests
|
||||
// restent corrects même exécutés contre une base déjà peuplée : comme le tri
|
||||
// est `created_at DESC`, les clients/users nouvellement créés sont toujours
|
||||
// les plus récents et apparaissent donc en tête de liste (offsets les plus
|
||||
// bas), quel que soit le volume de données préexistantes.
|
||||
package tests
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"testing"
|
||||
|
||||
"gestion/handlers"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// newTestUserRow crée une ligne dans la table users avec le rôle donné et
|
||||
// programme son nettoyage en fin de test.
|
||||
func newTestUserRow(t *testing.T, name, role string) string {
|
||||
t.Helper()
|
||||
username := testUserPrefix + name
|
||||
if err := testDB.GDB.Exec(
|
||||
`INSERT INTO users (username, password, role) VALUES (?, 'x', ?) ON CONFLICT (username) DO NOTHING`,
|
||||
username, role,
|
||||
).Error; err != nil {
|
||||
t.Fatalf("création user test %q: %v", username, err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
testDB.GDB.Exec(`DELETE FROM users WHERE username = ?`, username)
|
||||
})
|
||||
return username
|
||||
}
|
||||
|
||||
// ── db.GetAllClients ───────────────────────────────────────────────────────
|
||||
|
||||
func TestGetAllClients_PaginationIsConsistentAndCovers(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
|
||||
_, baseline, err := testDB.GetAllClients(1, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("GetAllClients (baseline): %v", err)
|
||||
}
|
||||
|
||||
a := newTestClient(t, "pg_cli_a")
|
||||
b := newTestClient(t, "pg_cli_b")
|
||||
c := newTestClient(t, "pg_cli_c")
|
||||
|
||||
page1, total1, err := testDB.GetAllClients(2, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("GetAllClients page1: %v", err)
|
||||
}
|
||||
page2, total2, err := testDB.GetAllClients(2, 2)
|
||||
if err != nil {
|
||||
t.Fatalf("GetAllClients page2: %v", err)
|
||||
}
|
||||
|
||||
wantTotal := baseline + 3
|
||||
if total1 != wantTotal || total2 != wantTotal {
|
||||
t.Fatalf("le total doit être stable entre deux pages et refléter les lignes réelles: total1=%d total2=%d want=%d", total1, total2, wantTotal)
|
||||
}
|
||||
if len(page1) != 2 {
|
||||
t.Fatalf("page1 (limit=2) doit contenir 2 clients: got=%d", len(page1))
|
||||
}
|
||||
wantPage2Len := int(total2) - 2
|
||||
if wantPage2Len > 2 {
|
||||
wantPage2Len = 2
|
||||
}
|
||||
if wantPage2Len < 0 {
|
||||
wantPage2Len = 0
|
||||
}
|
||||
if len(page2) != wantPage2Len {
|
||||
t.Fatalf("page2 (limit=2, offset=2, total=%d) doit contenir %d client(s): got=%d", total2, wantPage2Len, len(page2))
|
||||
}
|
||||
|
||||
seen := map[string]bool{}
|
||||
for _, cl := range page1 {
|
||||
if seen[cl.Username] {
|
||||
t.Errorf("doublon intra-page1: %q", cl.Username)
|
||||
}
|
||||
seen[cl.Username] = true
|
||||
}
|
||||
for _, cl := range page2 {
|
||||
if seen[cl.Username] {
|
||||
t.Errorf("le client %q apparaît sur deux pages consécutives : pagination incohérente", cl.Username)
|
||||
}
|
||||
seen[cl.Username] = true
|
||||
}
|
||||
// Les 3 clients créés sont les plus récents (created_at DESC) : ils sont
|
||||
// forcément dans les 4 premiers emplacements (page1 + page2 = offsets 0..3).
|
||||
for _, username := range []string{a, b, c} {
|
||||
if !seen[username] {
|
||||
t.Errorf("le client %q créé par le test n'apparaît sur aucune des deux pages", username)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Régression de la correction N+1 : GetAllClients doit renvoyer le parrain et
|
||||
// le motif de pénalité déjà en base dans le même appel, sans qu'il faille une
|
||||
// requête getClientParrain séparée par client.
|
||||
func TestGetAllClients_IncludesParrainAndLastPenaltyReason(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
parrain := newTestClient(t, "pg_parrain")
|
||||
filleul := newTestClient(t, "pg_filleul")
|
||||
|
||||
if err := testDB.SetClientParrainAndCredit(filleul, parrain, 0); err != nil {
|
||||
t.Fatalf("SetClientParrainAndCredit: %v", err)
|
||||
}
|
||||
if err := testDB.GDB.Exec(
|
||||
`UPDATE clients SET last_penalty_reason = ? WHERE username = ?`,
|
||||
"retard livraison", filleul,
|
||||
).Error; err != nil {
|
||||
t.Fatalf("UPDATE last_penalty_reason: %v", err)
|
||||
}
|
||||
|
||||
// Le filleul vient d'être créé/modifié : c'est la ligne la plus récente,
|
||||
// donc garantie en première position (offset 0) quel que soit le volume
|
||||
// de données existantes.
|
||||
clients, _, err := testDB.GetAllClients(1, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("GetAllClients: %v", err)
|
||||
}
|
||||
if len(clients) != 1 || clients[0].Username != filleul {
|
||||
t.Fatalf("le client le plus récemment créé doit être en tête de liste: got=%+v", clients)
|
||||
}
|
||||
|
||||
got := clients[0]
|
||||
if got.Parrain != parrain {
|
||||
t.Errorf("GetAllClients doit renvoyer le parrain déjà enregistré en base: got=%q want=%q", got.Parrain, parrain)
|
||||
}
|
||||
if got.LastPenaltyReason != "retard livraison" {
|
||||
t.Errorf("GetAllClients doit renvoyer last_penalty_reason: got=%q want=%q", got.LastPenaltyReason, "retard livraison")
|
||||
}
|
||||
}
|
||||
|
||||
// ── db.GetAllUsers ─────────────────────────────────────────────────────────
|
||||
|
||||
func TestGetAllUsers_PaginationIsConsistentAndCovers(t *testing.T) {
|
||||
_, baseline, err := testDB.GetAllUsers(1, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("GetAllUsers (baseline): %v", err)
|
||||
}
|
||||
|
||||
a := newTestUserRow(t, "pg_usr_a", "livreur")
|
||||
b := newTestUserRow(t, "pg_usr_b", "cabine")
|
||||
c := newTestUserRow(t, "pg_usr_c", "admin")
|
||||
|
||||
page1, total1, err := testDB.GetAllUsers(2, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("GetAllUsers page1: %v", err)
|
||||
}
|
||||
page2, total2, err := testDB.GetAllUsers(2, 2)
|
||||
if err != nil {
|
||||
t.Fatalf("GetAllUsers page2: %v", err)
|
||||
}
|
||||
|
||||
wantTotal := baseline + 3
|
||||
if total1 != wantTotal || total2 != wantTotal {
|
||||
t.Fatalf("le total doit être stable entre deux pages: total1=%d total2=%d want=%d", total1, total2, wantTotal)
|
||||
}
|
||||
if len(page1) != 2 {
|
||||
t.Fatalf("page1 (limit=2) doit contenir 2 users: got=%d", len(page1))
|
||||
}
|
||||
wantPage2Len := int(total2) - 2
|
||||
if wantPage2Len > 2 {
|
||||
wantPage2Len = 2
|
||||
}
|
||||
if wantPage2Len < 0 {
|
||||
wantPage2Len = 0
|
||||
}
|
||||
if len(page2) != wantPage2Len {
|
||||
t.Fatalf("page2 (limit=2, offset=2, total=%d) doit contenir %d user(s): got=%d", total2, wantPage2Len, len(page2))
|
||||
}
|
||||
|
||||
seen := map[string]bool{}
|
||||
for _, u := range page1 {
|
||||
seen[u.Username] = true
|
||||
}
|
||||
for _, u := range page2 {
|
||||
if seen[u.Username] {
|
||||
t.Errorf("le user %q apparaît sur deux pages consécutives : pagination incohérente", u.Username)
|
||||
}
|
||||
seen[u.Username] = true
|
||||
}
|
||||
for _, username := range []string{a, b, c} {
|
||||
if !seen[username] {
|
||||
t.Errorf("le user %q créé par le test n'apparaît sur aucune des deux pages", username)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── Handlers : query params, clamp, count/has_more ──────────────────────────
|
||||
|
||||
type pagedListResponse struct {
|
||||
Clients []struct {
|
||||
Username string `json:"username"`
|
||||
} `json:"clients"`
|
||||
Users []struct {
|
||||
Username string `json:"username"`
|
||||
} `json:"users"`
|
||||
Count int64 `json:"count"`
|
||||
HasMore bool `json:"has_more"`
|
||||
}
|
||||
|
||||
func clientsListContext(role string, query url.Values) (*gin.Context, *httptest.ResponseRecorder) {
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v2/admin/protected/all/clients?"+query.Encode(), nil)
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
c.Request = req
|
||||
c.Set("database", testDB)
|
||||
c.Set("role", role)
|
||||
return c, rec
|
||||
}
|
||||
|
||||
func usersListContext(role string, query url.Values) (*gin.Context, *httptest.ResponseRecorder) {
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v2/admin/protected/all/users?"+query.Encode(), nil)
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
c.Request = req
|
||||
c.Set("database", testDB)
|
||||
c.Set("role", role)
|
||||
return c, rec
|
||||
}
|
||||
|
||||
func TestGetAllClientsHandler_RejectsNonAdminNonCabine(t *testing.T) {
|
||||
c, rec := clientsListContext("livreur", url.Values{})
|
||||
handlers.GetAllClients(c)
|
||||
if rec.Code != http.StatusForbidden {
|
||||
t.Errorf("role livreur doit être refusé: got=%d want=403", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetAllClientsHandler_ClampsLimitAndReportsRealTotal(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
_, baseline, err := testDB.GetAllClients(1, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("baseline: %v", err)
|
||||
}
|
||||
newTestClient(t, "pg_h_cli_a")
|
||||
newTestClient(t, "pg_h_cli_b")
|
||||
newTestClient(t, "pg_h_cli_c")
|
||||
wantTotal := baseline + 3
|
||||
|
||||
q := url.Values{}
|
||||
q.Set("limit", "1000") // doit être plafonné à 100 côté serveur
|
||||
c, rec := clientsListContext("admin", q)
|
||||
handlers.GetAllClients(c)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("got=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
var resp pagedListResponse
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
|
||||
t.Fatalf("décodage réponse: %v body=%s", err, rec.Body.String())
|
||||
}
|
||||
if len(resp.Clients) > 100 {
|
||||
t.Errorf("limit doit être plafonnée à 100 côté serveur même si le client en demande 1000: got=%d", len(resp.Clients))
|
||||
}
|
||||
if resp.Count != wantTotal {
|
||||
t.Errorf("count doit être le total réel en base, pas la taille de la page renvoyée: got=%d want=%d", resp.Count, wantTotal)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetAllClientsHandler_HasMoreReflectsRemainingRows(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
_, baseline, err := testDB.GetAllClients(1, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("baseline: %v", err)
|
||||
}
|
||||
newTestClient(t, "pg_h_hm_a")
|
||||
newTestClient(t, "pg_h_hm_b")
|
||||
newTestClient(t, "pg_h_hm_c")
|
||||
total := baseline + 3
|
||||
|
||||
q := url.Values{}
|
||||
q.Set("limit", "2")
|
||||
q.Set("offset", "0")
|
||||
c, rec := clientsListContext("admin", q)
|
||||
handlers.GetAllClients(c)
|
||||
var resp pagedListResponse
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
|
||||
t.Fatalf("décodage réponse: %v body=%s", err, rec.Body.String())
|
||||
}
|
||||
if !resp.HasMore {
|
||||
t.Errorf("has_more doit être true: offset(0)+limit(2)=2 < total(%d)", total)
|
||||
}
|
||||
|
||||
q2 := url.Values{}
|
||||
q2.Set("limit", "2")
|
||||
q2.Set("offset", fmt.Sprintf("%d", total-1))
|
||||
c2, rec2 := clientsListContext("admin", q2)
|
||||
handlers.GetAllClients(c2)
|
||||
var resp2 pagedListResponse
|
||||
if err := json.Unmarshal(rec2.Body.Bytes(), &resp2); err != nil {
|
||||
t.Fatalf("décodage réponse: %v body=%s", err, rec2.Body.String())
|
||||
}
|
||||
if resp2.HasMore {
|
||||
t.Errorf("has_more doit être false à la dernière page: offset=%d total=%d", total-1, total)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetAllUsersHandler_RejectsNonAdminNonCabine(t *testing.T) {
|
||||
c, rec := usersListContext("livreur", url.Values{})
|
||||
handlers.GetAllUsers(c)
|
||||
if rec.Code != http.StatusForbidden {
|
||||
t.Errorf("role livreur doit être refusé: got=%d want=403", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetAllUsersHandler_ClampsLimitAndReportsRealTotal(t *testing.T) {
|
||||
_, baseline, err := testDB.GetAllUsers(1, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("baseline: %v", err)
|
||||
}
|
||||
newTestUserRow(t, "pg_h_usr_a", "livreur")
|
||||
newTestUserRow(t, "pg_h_usr_b", "cabine")
|
||||
newTestUserRow(t, "pg_h_usr_c", "admin")
|
||||
wantTotal := baseline + 3
|
||||
|
||||
q := url.Values{}
|
||||
q.Set("limit", "1000")
|
||||
c, rec := usersListContext("admin", q)
|
||||
handlers.GetAllUsers(c)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("got=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
var resp pagedListResponse
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
|
||||
t.Fatalf("décodage réponse: %v body=%s", err, rec.Body.String())
|
||||
}
|
||||
if len(resp.Users) > 100 {
|
||||
t.Errorf("limit doit être plafonnée à 100 côté serveur même si le client en demande 1000: got=%d", len(resp.Users))
|
||||
}
|
||||
if resp.Count != wantTotal {
|
||||
t.Errorf("count doit être le total réel en base, pas la taille de la page renvoyée: got=%d want=%d", resp.Count, wantTotal)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetAllUsersHandler_HasMoreReflectsRemainingRows(t *testing.T) {
|
||||
_, baseline, err := testDB.GetAllUsers(1, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("baseline: %v", err)
|
||||
}
|
||||
newTestUserRow(t, "pg_h_usr_hm_a", "livreur")
|
||||
newTestUserRow(t, "pg_h_usr_hm_b", "cabine")
|
||||
newTestUserRow(t, "pg_h_usr_hm_c", "admin")
|
||||
total := baseline + 3
|
||||
|
||||
q := url.Values{}
|
||||
q.Set("limit", "2")
|
||||
q.Set("offset", "0")
|
||||
c, rec := usersListContext("admin", q)
|
||||
handlers.GetAllUsers(c)
|
||||
var resp pagedListResponse
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
|
||||
t.Fatalf("décodage réponse: %v body=%s", err, rec.Body.String())
|
||||
}
|
||||
if !resp.HasMore {
|
||||
t.Errorf("has_more doit être true: offset(0)+limit(2)=2 < total(%d)", total)
|
||||
}
|
||||
|
||||
q2 := url.Values{}
|
||||
q2.Set("limit", "2")
|
||||
q2.Set("offset", fmt.Sprintf("%d", total-1))
|
||||
c2, rec2 := usersListContext("admin", q2)
|
||||
handlers.GetAllUsers(c2)
|
||||
var resp2 pagedListResponse
|
||||
if err := json.Unmarshal(rec2.Body.Bytes(), &resp2); err != nil {
|
||||
t.Fatalf("décodage réponse: %v body=%s", err, rec2.Body.String())
|
||||
}
|
||||
if resp2.HasMore {
|
||||
t.Errorf("has_more doit être false à la dernière page: offset=%d total=%d", total-1, total)
|
||||
}
|
||||
}
|
||||
|
||||
// ── Paramètres invalides : retour aux valeurs par défaut ────────────────────
|
||||
|
||||
// listUsernames appelle le handler avec les query params donnés et renvoie les
|
||||
// usernames de la page, dans l'ordre de la réponse.
|
||||
func listUsernames(t *testing.T, handler func(*gin.Context), ctx func(string, url.Values) (*gin.Context, *httptest.ResponseRecorder), q url.Values) []string {
|
||||
t.Helper()
|
||||
c, rec := ctx("admin", q)
|
||||
handler(c)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("query %q: got=%d body=%s", q.Encode(), rec.Code, rec.Body.String())
|
||||
}
|
||||
var resp pagedListResponse
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
|
||||
t.Fatalf("décodage réponse: %v body=%s", err, rec.Body.String())
|
||||
}
|
||||
var names []string
|
||||
for _, cl := range resp.Clients {
|
||||
names = append(names, cl.Username)
|
||||
}
|
||||
for _, u := range resp.Users {
|
||||
names = append(names, u.Username)
|
||||
}
|
||||
return names
|
||||
}
|
||||
|
||||
var invalidPaginationQueries = []struct {
|
||||
name, key, value string
|
||||
}{
|
||||
{"limit non numérique", "limit", "abc"},
|
||||
{"limit négatif", "limit", "-1"},
|
||||
{"limit à zéro", "limit", "0"},
|
||||
{"offset non numérique", "offset", "abc"},
|
||||
{"offset négatif", "offset", "-1"},
|
||||
}
|
||||
|
||||
// Une valeur invalide ne doit ni faire échouer la requête ni être appliquée :
|
||||
// la page renvoyée doit être identique à celle obtenue sans paramètre
|
||||
// (limit=100, offset=0).
|
||||
func assertInvalidParamsFallBackToDefaults(t *testing.T, handler func(*gin.Context), ctx func(string, url.Values) (*gin.Context, *httptest.ResponseRecorder)) {
|
||||
t.Helper()
|
||||
want := listUsernames(t, handler, ctx, url.Values{})
|
||||
if len(want) == 0 {
|
||||
t.Fatal("la page par défaut ne doit pas être vide (données de test créées)")
|
||||
}
|
||||
for _, tc := range invalidPaginationQueries {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
q := url.Values{}
|
||||
q.Set(tc.key, tc.value)
|
||||
got := listUsernames(t, handler, ctx, q)
|
||||
if len(got) != len(want) || got[0] != want[0] {
|
||||
t.Errorf("%s=%s doit revenir aux valeurs par défaut: got len=%d first=%v want len=%d first=%q",
|
||||
tc.key, tc.value, len(got), got, len(want), want[0])
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetAllClientsHandler_InvalidParamsFallBackToDefaults(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
newTestClient(t, "pg_inv_cli_a")
|
||||
newTestClient(t, "pg_inv_cli_b")
|
||||
newTestClient(t, "pg_inv_cli_c")
|
||||
assertInvalidParamsFallBackToDefaults(t, handlers.GetAllClients, clientsListContext)
|
||||
}
|
||||
|
||||
func TestGetAllUsersHandler_InvalidParamsFallBackToDefaults(t *testing.T) {
|
||||
newTestUserRow(t, "pg_inv_usr_a", "livreur")
|
||||
newTestUserRow(t, "pg_inv_usr_b", "cabine")
|
||||
newTestUserRow(t, "pg_inv_usr_c", "admin")
|
||||
assertInvalidParamsFallBackToDefaults(t, handlers.GetAllUsers, usersListContext)
|
||||
}
|
||||
@@ -51,15 +51,16 @@ func TestTotalRevenue_NetsReferralAndExcludesNonApproved(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TotalOrders exclut uniquement les commandes annulées (contrairement à
|
||||
// TotalRevenue, il compte aussi les commandes non encore approuvées).
|
||||
func TestTotalOrders_ExcludesOnlyCancelled(t *testing.T) {
|
||||
// TotalOrders compte uniquement les commandes actives (même périmètre que le
|
||||
// dashboard) : les commandes terminées (approved) et annulées sont exclues.
|
||||
func TestTotalOrders_CountsOnlyActiveOrders(t *testing.T) {
|
||||
cleanupStockTestData(t)
|
||||
username := newTestClient(t, "stats_total_orders")
|
||||
productID := newTestProduct(t, "StatsTotalOrders", 100)
|
||||
now := time.Now()
|
||||
|
||||
newTestOrderForStats(t, username, "pending", productID, 1, 10, 0, now)
|
||||
newTestOrderForStats(t, username, "en_route", productID, 1, 10, 0, now)
|
||||
newTestOrderForStats(t, username, "approved", productID, 1, 10, 0, now)
|
||||
newTestOrderForStats(t, username, "cancelled", productID, 1, 10, 0, now)
|
||||
|
||||
@@ -68,7 +69,7 @@ func TestTotalOrders_ExcludesOnlyCancelled(t *testing.T) {
|
||||
t.Fatalf("TotalOrders: %v", err)
|
||||
}
|
||||
if total != 2 {
|
||||
t.Errorf("TotalOrders: got=%d want=2 (pending+approved, cancelled exclue)", total)
|
||||
t.Errorf("TotalOrders: got=%d want=2 (pending+en_route ; approved et cancelled exclues)", total)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user