chore: build
This commit is contained in:
@@ -76,8 +76,9 @@ func (d *Database) GetClientByID(id int) (*models.Client, error) {
|
|||||||
return client, nil
|
return client, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetAllClients récupère tous les clients
|
// GetAllClients récupère une page de clients, triée par date de création
|
||||||
func (d *Database) GetAllClients() ([]*models.Client, error) {
|
// descendante, ainsi que le nombre total de clients en base.
|
||||||
|
func (d *Database) GetAllClients(limit, offset int) ([]*models.Client, int64, error) {
|
||||||
var rows []struct {
|
var rows []struct {
|
||||||
ID int `gorm:"column:id"`
|
ID int `gorm:"column:id"`
|
||||||
Username string `gorm:"column:username"`
|
Username string `gorm:"column:username"`
|
||||||
@@ -89,16 +90,25 @@ func (d *Database) GetAllClients() ([]*models.Client, error) {
|
|||||||
Amende float64 `gorm:"column:amende"`
|
Amende float64 `gorm:"column:amende"`
|
||||||
ReferralBalance float64 `gorm:"column:referral_balance"`
|
ReferralBalance float64 `gorm:"column:referral_balance"`
|
||||||
CancellationsCount int `gorm:"column:cancellations_count"`
|
CancellationsCount int `gorm:"column:cancellations_count"`
|
||||||
|
LastPenaltyReason string `gorm:"column:last_penalty_reason"`
|
||||||
|
Parrain string `gorm:"column:parrain"`
|
||||||
PointsExtraJSON []byte `gorm:"column:points_extra"`
|
PointsExtraJSON []byte `gorm:"column:points_extra"`
|
||||||
CreatedAt time.Time `gorm:"column:created_at"`
|
CreatedAt time.Time `gorm:"column:created_at"`
|
||||||
}
|
}
|
||||||
err := d.GDB.Raw(`
|
err := d.GDB.Raw(`
|
||||||
SELECT id, username, password, nom, prenom, telephone, command, amende, referral_balance,
|
SELECT id, username, password, nom, prenom, telephone, command, amende, referral_balance,
|
||||||
COALESCE(cancellations_count, 0) as cancellations_count,
|
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
|
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 {
|
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))
|
clients := make([]*models.Client, 0, len(rows))
|
||||||
@@ -114,6 +124,8 @@ func (d *Database) GetAllClients() ([]*models.Client, error) {
|
|||||||
Amende: row.Amende,
|
Amende: row.Amende,
|
||||||
ReferralBalance: row.ReferralBalance,
|
ReferralBalance: row.ReferralBalance,
|
||||||
CancellationsCount: row.CancellationsCount,
|
CancellationsCount: row.CancellationsCount,
|
||||||
|
LastPenaltyReason: row.LastPenaltyReason,
|
||||||
|
Parrain: row.Parrain,
|
||||||
CreatedAt: row.CreatedAt,
|
CreatedAt: row.CreatedAt,
|
||||||
}
|
}
|
||||||
client.PointsExtra = map[string]int{}
|
client.PointsExtra = map[string]int{}
|
||||||
@@ -123,7 +135,7 @@ func (d *Database) GetAllClients() ([]*models.Client, error) {
|
|||||||
clients = append(clients, client)
|
clients = append(clients, client)
|
||||||
}
|
}
|
||||||
|
|
||||||
return clients, nil
|
return clients, total, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// UpdateClient met à jour un client existant
|
// UpdateClient met à jour un client existant
|
||||||
|
|||||||
@@ -6,10 +6,13 @@
|
|||||||
package db
|
package db
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"log"
|
"log"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/redis/go-redis/v9"
|
||||||
)
|
)
|
||||||
|
|
||||||
var allowedStatuses = map[string]bool{
|
var allowedStatuses = map[string]bool{
|
||||||
@@ -98,6 +101,138 @@ func ValidateStatuses(statuses string) ([]string, error) {
|
|||||||
return cleanStatuses, nil
|
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
|
// GetLastDeliveryDate récupère la date de la dernière livraison d'un livreur
|
||||||
func (d *Database) GetLastDeliveryDate(livreurUsername string) (*time.Time, error) {
|
func (d *Database) GetLastDeliveryDate(livreurUsername string) (*time.Time, error) {
|
||||||
var result struct {
|
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_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_telephone ON clients(telephone);`,
|
||||||
`CREATE INDEX IF NOT EXISTS idx_clients_cancellations ON clients(cancellations_count);`,
|
`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_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_username ON commandes(username);`,
|
||||||
`CREATE INDEX IF NOT EXISTS idx_cmd_status ON commandes(status);`,
|
`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
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (d *Database) GetAllUsers() ([]*models.User, error) {
|
func (d *Database) GetAllUsers(limit, offset int) ([]*models.User, int64, error) {
|
||||||
var users []*models.User
|
var users []*models.User
|
||||||
if err := d.GDB.Order("created_at DESC").Limit(500).Find(&users).Error; err != nil {
|
if err := d.GDB.Order("created_at DESC").Limit(limit).Offset(offset).Find(&users).Error; err != nil {
|
||||||
return nil, fmt.Errorf("erreur lors de la récupération des utilisateurs: %w", err)
|
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) {
|
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"})
|
c.JSON(http.StatusForbidden, gin.H{"error": "Accès réservé aux livreurs et aux administrateurs"})
|
||||||
return
|
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 {
|
if err != nil {
|
||||||
log.Printf("❌ [GET_ALL_USERS] Erreur: %v", err)
|
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{
|
c.JSON(http.StatusOK, gin.H{
|
||||||
"users": sanitized,
|
"users": sanitized,
|
||||||
"count": len(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"})
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "Erreur récupération"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
usernames := make([]string, len(users))
|
||||||
|
for i, u := range users {
|
||||||
|
usernames[i] = u.Username
|
||||||
|
}
|
||||||
|
detailsByUsername := database.GetDeliveryPersonsDetailsBatch(usernames)
|
||||||
|
|
||||||
var sanitized []gin.H
|
var sanitized []gin.H
|
||||||
for _, u := range users {
|
for _, u := range users {
|
||||||
sanitized = append(sanitized, gin.H{
|
det := detailsByUsername[u.Username]
|
||||||
"id": u.ID,
|
if det == nil {
|
||||||
"username": u.Username,
|
det = &db.DeliveryPersonDetails{Status: "offline"}
|
||||||
"role": u.Role,
|
}
|
||||||
})
|
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))
|
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"})
|
c.JSON(http.StatusForbidden, gin.H{"error": "Accès réservé aux livreurs et aux administrateurs"})
|
||||||
return
|
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 {
|
if err != nil {
|
||||||
log.Printf("❌ [GET_ALL_CLIENTS] Erreur: %v", err)
|
log.Printf("❌ [GET_ALL_CLIENTS] Erreur: %v", err)
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "Erreur récupération"})
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "Erreur récupération"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
limited := rateLimitedClients(clients)
|
||||||
|
|
||||||
var sanitized []gin.H
|
var sanitized []gin.H
|
||||||
for _, cl := range clients {
|
for _, cl := range clients {
|
||||||
sanitized = append(sanitized, gin.H{
|
sanitized = append(sanitized, gin.H{
|
||||||
|
"rate_limited": limited[cl.Username],
|
||||||
"id": cl.ID,
|
"id": cl.ID,
|
||||||
"username": cl.Username,
|
"username": cl.Username,
|
||||||
"nom": cl.Nom,
|
"nom": cl.Nom,
|
||||||
@@ -596,14 +654,16 @@ func GetAllClients(c *gin.Context) {
|
|||||||
"cancellations_count": cl.CancellationsCount,
|
"cancellations_count": cl.CancellationsCount,
|
||||||
"last_penalty_reason": cl.LastPenaltyReason,
|
"last_penalty_reason": cl.LastPenaltyReason,
|
||||||
"referral_balance": cl.ReferralBalance,
|
"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{
|
c.JSON(http.StatusOK, gin.H{
|
||||||
"clients": sanitized,
|
"clients": sanitized,
|
||||||
"count": len(sanitized),
|
"count": total,
|
||||||
|
"has_more": int64(offset+len(clients)) < total,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
@@ -14,11 +15,26 @@ import (
|
|||||||
|
|
||||||
var (
|
var (
|
||||||
cancelRateLimitMap = make(map[string][]time.Time)
|
cancelRateLimitMap = make(map[string][]time.Time)
|
||||||
|
cancelRateLimitMu sync.Mutex
|
||||||
cancelMaxRequests = 5 // Max 5 annulations
|
cancelMaxRequests = 5 // Max 5 annulations
|
||||||
cancelTimeWindow = time.Hour // Par heure
|
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 {
|
func checkCancelRateLimit(key string) bool {
|
||||||
|
cancelRateLimitMu.Lock()
|
||||||
|
defer cancelRateLimitMu.Unlock()
|
||||||
now := time.Now()
|
now := time.Now()
|
||||||
|
|
||||||
if timestamps, exists := cancelRateLimitMap[key]; exists {
|
if timestamps, exists := cancelRateLimitMap[key]; exists {
|
||||||
@@ -67,7 +83,7 @@ func CancelCommandByClient(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
rateLimitKey := fmt.Sprintf("cancel:%s", username)
|
rateLimitKey := cancelRateLimitKey(username)
|
||||||
if !checkCancelRateLimit(rateLimitKey) {
|
if !checkCancelRateLimit(rateLimitKey) {
|
||||||
log.Printf("⚠️ [CANCEL_CLIENT] Rate limit dépassé pour %s", username)
|
log.Printf("⚠️ [CANCEL_CLIENT] Rate limit dépassé pour %s", username)
|
||||||
c.JSON(http.StatusTooManyRequests, gin.H{
|
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
|
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) {
|
func safeGetUsername(c *gin.Context) (string, error) {
|
||||||
username, exists := c.Get("username")
|
username, exists := c.Get("username")
|
||||||
if !exists {
|
if !exists {
|
||||||
@@ -356,7 +380,7 @@ func UpdateOwnCommandAddress(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
rateLimitKey := fmt.Sprintf("update_own_addr:%s", clientUsername)
|
rateLimitKey := ownAddressRateLimitKey(clientUsername)
|
||||||
if !checkRateLimit(rateLimitKey) {
|
if !checkRateLimit(rateLimitKey) {
|
||||||
c.JSON(http.StatusTooManyRequests, gin.H{"error": "Trop de requêtes, réessayez plus tard"})
|
c.JSON(http.StatusTooManyRequests, gin.H{"error": "Trop de requêtes, réessayez plus tard"})
|
||||||
return
|
return
|
||||||
@@ -746,6 +770,39 @@ func GetAvailableDeliveryPersons(c *gin.Context) {
|
|||||||
return
|
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))
|
log.Printf("✅ [GET_LIVREURS] Trouvés: %d livreurs disponibles", len(livreurs))
|
||||||
|
|
||||||
c.JSON(http.StatusOK, gin.H{
|
c.JSON(http.StatusOK, gin.H{
|
||||||
|
|||||||
@@ -437,6 +437,13 @@ func ClientSessionMiddleware(c *gin.Context) {
|
|||||||
c.Next()
|
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) {
|
func RateLimitMiddleware(c *gin.Context) {
|
||||||
// Récupérer le client_id
|
// Récupérer le client_id
|
||||||
clientID, ok := c.Get("client_id")
|
clientID, ok := c.Get("client_id")
|
||||||
@@ -446,7 +453,7 @@ func RateLimitMiddleware(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
clientIDInt := clientID.(int)
|
clientIDInt := clientID.(int)
|
||||||
rateLimitKey := "ratelimit:" + strconv.Itoa(clientIDInt)
|
rateLimitKey := ClientRateLimitKey(clientIDInt)
|
||||||
|
|
||||||
// Incrémenter le compteur
|
// Incrémenter le compteur
|
||||||
count, err := db.Redis.Incr(db.RedisCtx, rateLimitKey).Result()
|
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
|
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)
|
log.Printf("❌ [RATELIMIT] Client %d dépassé le limite: %d requêtes/min", clientIDInt, count)
|
||||||
c.JSON(http.StatusTooManyRequests, gin.H{
|
c.JSON(http.StatusTooManyRequests, gin.H{
|
||||||
"error": "Trop de requêtes - Réessayez dans une minute",
|
"error": "Trop de requêtes - Réessayez dans une minute",
|
||||||
@@ -469,9 +476,9 @@ func RateLimitMiddleware(c *gin.Context) {
|
|||||||
return
|
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()
|
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/add", handlers.AddClientPointsAdmin) // Ajouter points par pool
|
||||||
adminGroupV2.POST("/client/:username/points/subtract", handlers.SubtractClientPointsAdmin) // Enlever 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/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/all", handlers.GetAllClientsWithPenalties) // Liste clients avec pénalités
|
||||||
adminGroupV2.GET("/penalties/stats", handlers.GetPenaltiesStats)
|
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) {
|
func TestMain(m *testing.M) {
|
||||||
gin.SetMode(gin.TestMode)
|
gin.SetMode(gin.TestMode)
|
||||||
testDB = db.InitDB()
|
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()
|
db.InitRedis()
|
||||||
os.Exit(m.Run())
|
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 à
|
// TotalOrders compte uniquement les commandes actives (même périmètre que le
|
||||||
// TotalRevenue, il compte aussi les commandes non encore approuvées).
|
// dashboard) : les commandes terminées (approved) et annulées sont exclues.
|
||||||
func TestTotalOrders_ExcludesOnlyCancelled(t *testing.T) {
|
func TestTotalOrders_CountsOnlyActiveOrders(t *testing.T) {
|
||||||
cleanupStockTestData(t)
|
cleanupStockTestData(t)
|
||||||
username := newTestClient(t, "stats_total_orders")
|
username := newTestClient(t, "stats_total_orders")
|
||||||
productID := newTestProduct(t, "StatsTotalOrders", 100)
|
productID := newTestProduct(t, "StatsTotalOrders", 100)
|
||||||
now := time.Now()
|
now := time.Now()
|
||||||
|
|
||||||
newTestOrderForStats(t, username, "pending", productID, 1, 10, 0, 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, "approved", productID, 1, 10, 0, now)
|
||||||
newTestOrderForStats(t, username, "cancelled", 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)
|
t.Fatalf("TotalOrders: %v", err)
|
||||||
}
|
}
|
||||||
if total != 2 {
|
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)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -207,14 +207,44 @@ export const getAdminStatsByMonth = async (
|
|||||||
);
|
);
|
||||||
return data;
|
return data;
|
||||||
};
|
};
|
||||||
export const getAllClients = async (): Promise<ClientResponse[]> => {
|
export interface AdminUserItem {
|
||||||
const { data } = await apiClient.get(`${V2}/admin/protected/all/clients`);
|
id: number;
|
||||||
return data.clients || [];
|
username: string;
|
||||||
|
role: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PagedResult<T> {
|
||||||
|
items: T[];
|
||||||
|
total: number;
|
||||||
|
hasMore: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const getAllClients = async (
|
||||||
|
offset = 0,
|
||||||
|
limit = 100,
|
||||||
|
): Promise<PagedResult<ClientResponse>> => {
|
||||||
|
const { data } = await apiClient.get(`${V2}/admin/protected/all/clients`, {
|
||||||
|
params: { limit, offset },
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
items: data.clients || [],
|
||||||
|
total: data.count ?? 0,
|
||||||
|
hasMore: !!data.has_more,
|
||||||
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
export const getAllUsers = async () => {
|
export const getAllUsers = async (
|
||||||
const { data } = await apiClient.get(`${V2}/admin/protected/all/users`);
|
offset = 0,
|
||||||
return data.users || [];
|
limit = 100,
|
||||||
|
): Promise<PagedResult<AdminUserItem>> => {
|
||||||
|
const { data } = await apiClient.get(`${V2}/admin/protected/all/users`, {
|
||||||
|
params: { limit, offset },
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
items: data.users || [],
|
||||||
|
total: data.count ?? 0,
|
||||||
|
hasMore: !!data.has_more,
|
||||||
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
export const updateClientByAdmin = async (
|
export const updateClientByAdmin = async (
|
||||||
@@ -489,60 +519,37 @@ export const getAllDeliveryPersonsWithDetails = async (): Promise<{
|
|||||||
stats: DeliveryPersonsStats;
|
stats: DeliveryPersonsStats;
|
||||||
}> => {
|
}> => {
|
||||||
try {
|
try {
|
||||||
|
// Le backend renvoie désormais statut/position/compteurs déjà
|
||||||
|
// enrichis pour tous les livreurs en un seul appel (voir
|
||||||
|
// GetDeliveryPersonsDetailsBatch côté backend) : plus besoin d'un
|
||||||
|
// aller-retour /delivery-persons/:username par livreur ici.
|
||||||
const { data } = await apiClient.get(
|
const { data } = await apiClient.get(
|
||||||
`${V2}/admin/protected/delivery-persons`,
|
`${V2}/admin/protected/delivery-persons`,
|
||||||
);
|
);
|
||||||
const livreurs = data.livreurs || [];
|
const livreurs = data.livreurs || [];
|
||||||
|
|
||||||
const enriched = await Promise.all(
|
const enriched: DeliveryPerson[] = livreurs.map(
|
||||||
livreurs.map(async (l: any): Promise<DeliveryPerson> => {
|
(l: any): DeliveryPerson => {
|
||||||
try {
|
const parsedStatus = parseStatus(l.status);
|
||||||
const details = await getDeliveryPersonDetails(l.username);
|
const hasLoc = l.location?.latitude && l.location?.longitude;
|
||||||
const parsedStatus = parseStatus(details.status);
|
return {
|
||||||
const hasLoc =
|
id: l.id,
|
||||||
details.location?.latitude &&
|
username: l.username,
|
||||||
details.location?.longitude;
|
status: parsedStatus,
|
||||||
return {
|
location: {
|
||||||
id: l.id,
|
latitude: hasLoc ? l.location.latitude : 0,
|
||||||
username: l.username,
|
longitude: hasLoc ? l.location.longitude : 0,
|
||||||
status: parsedStatus,
|
last_update: new Date().toISOString(),
|
||||||
location: {
|
is_recent: false,
|
||||||
latitude: hasLoc ? details.location.latitude : 0,
|
},
|
||||||
longitude: hasLoc ? details.location.longitude : 0,
|
stats: {
|
||||||
last_update: details.location?.last_update
|
total_deliveries: l.total_deliveries || 0,
|
||||||
? new Date(
|
completed_today: l.completed_deliveries || 0,
|
||||||
details.location.last_update * 1000,
|
queue_size: l.queue_size || 0,
|
||||||
).toISOString()
|
current_command: l.current_command || null,
|
||||||
: new Date().toISOString(),
|
},
|
||||||
is_recent: details.location?.is_recent || false,
|
};
|
||||||
},
|
},
|
||||||
stats: {
|
|
||||||
total_deliveries: details.total_deliveries || 0,
|
|
||||||
completed_today: details.completed_deliveries || 0,
|
|
||||||
queue_size: details.queue_size || 0,
|
|
||||||
current_command: details.current_command || null,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
} catch {
|
|
||||||
return {
|
|
||||||
id: l.id,
|
|
||||||
username: l.username,
|
|
||||||
status: "offline",
|
|
||||||
location: {
|
|
||||||
latitude: 0,
|
|
||||||
longitude: 0,
|
|
||||||
last_update: new Date().toISOString(),
|
|
||||||
is_recent: false,
|
|
||||||
},
|
|
||||||
stats: {
|
|
||||||
total_deliveries: 0,
|
|
||||||
completed_today: 0,
|
|
||||||
queue_size: 0,
|
|
||||||
current_command: null,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}),
|
|
||||||
);
|
);
|
||||||
|
|
||||||
const stats: DeliveryPersonsStats = {
|
const stats: DeliveryPersonsStats = {
|
||||||
@@ -755,6 +762,22 @@ export const getClientReferralAdmin = async (
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export const resetClientRateLimit = async (
|
||||||
|
username: string,
|
||||||
|
): Promise<{ success: boolean; error?: string }> => {
|
||||||
|
try {
|
||||||
|
await apiClient.post(
|
||||||
|
`${V2}/admin/protected/client/${username}/ratelimit/reset`,
|
||||||
|
);
|
||||||
|
return { success: true };
|
||||||
|
} catch (e: any) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: e.response?.data?.error || "Erreur levée du rate limit",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
export const resetClientReferral = async (
|
export const resetClientReferral = async (
|
||||||
username: string,
|
username: string,
|
||||||
): Promise<{ success: boolean; message?: string }> => {
|
): Promise<{ success: boolean; message?: string }> => {
|
||||||
|
|||||||
@@ -186,60 +186,35 @@ export const getAllDeliveryPersonsWithDetails = async (): Promise<{
|
|||||||
stats: DeliveryPersonsStats;
|
stats: DeliveryPersonsStats;
|
||||||
}> => {
|
}> => {
|
||||||
try {
|
try {
|
||||||
|
// Le backend renvoie désormais statut/position/compteurs déjà
|
||||||
|
// enrichis pour tous les livreurs en un seul appel (voir
|
||||||
|
// GetDeliveryPersonsDetailsBatch côté backend) : plus besoin d'un
|
||||||
|
// aller-retour /delivery-persons/:username par livreur ici.
|
||||||
const { data } = await apiClient.get(`${API}/all/deliveryman`);
|
const { data } = await apiClient.get(`${API}/all/deliveryman`);
|
||||||
const users = data.users || [];
|
const users = data.users || [];
|
||||||
|
|
||||||
const enriched = await Promise.all(
|
const enriched: DeliveryPerson[] = users.map(
|
||||||
users.map(async (u: any): Promise<DeliveryPerson> => {
|
(u: any): DeliveryPerson => {
|
||||||
try {
|
const parsedStatus = parseStatus(u.status);
|
||||||
const { data: details } = await apiClient.get(
|
const hasLoc = u.location?.latitude && u.location?.longitude;
|
||||||
`${API}/delivery-persons/${u.username}`,
|
return {
|
||||||
);
|
id: u.id,
|
||||||
const d = details.deliveryman || details;
|
username: u.username,
|
||||||
const parsedStatus = parseStatus(d.status);
|
status: parsedStatus,
|
||||||
const hasLoc =
|
location: {
|
||||||
d.location?.latitude && d.location?.longitude;
|
latitude: hasLoc ? u.location.latitude : 0,
|
||||||
return {
|
longitude: hasLoc ? u.location.longitude : 0,
|
||||||
id: u.id,
|
last_update: new Date().toISOString(),
|
||||||
username: u.username,
|
is_recent: false,
|
||||||
status: parsedStatus,
|
},
|
||||||
location: {
|
stats: {
|
||||||
latitude: hasLoc ? d.location.latitude : 0,
|
total_deliveries: u.total_deliveries || 0,
|
||||||
longitude: hasLoc ? d.location.longitude : 0,
|
completed_today: u.completed_deliveries || 0,
|
||||||
last_update: d.location?.last_update
|
queue_size: u.queue_size || 0,
|
||||||
? new Date(
|
current_command: u.current_command || null,
|
||||||
d.location.last_update * 1000,
|
},
|
||||||
).toISOString()
|
};
|
||||||
: new Date().toISOString(),
|
},
|
||||||
is_recent: d.location?.is_recent || false,
|
|
||||||
},
|
|
||||||
stats: {
|
|
||||||
total_deliveries: d.total_deliveries || 0,
|
|
||||||
completed_today: d.completed_deliveries || 0,
|
|
||||||
queue_size: d.queue_size || 0,
|
|
||||||
current_command: d.current_command || null,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
} catch {
|
|
||||||
return {
|
|
||||||
id: u.id,
|
|
||||||
username: u.username,
|
|
||||||
status: "offline",
|
|
||||||
location: {
|
|
||||||
latitude: 0,
|
|
||||||
longitude: 0,
|
|
||||||
last_update: new Date().toISOString(),
|
|
||||||
is_recent: false,
|
|
||||||
},
|
|
||||||
stats: {
|
|
||||||
total_deliveries: 0,
|
|
||||||
completed_today: 0,
|
|
||||||
queue_size: 0,
|
|
||||||
current_command: null,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}),
|
|
||||||
);
|
);
|
||||||
|
|
||||||
const stats: DeliveryPersonsStats = {
|
const stats: DeliveryPersonsStats = {
|
||||||
@@ -447,10 +422,23 @@ export const getCabineCommands = async (): Promise<{
|
|||||||
// CLIENTS — CABINE
|
// CLIENTS — CABINE
|
||||||
// ============================================
|
// ============================================
|
||||||
|
|
||||||
|
// Le backend pagine désormais cette route (100 clients par page) ; on boucle
|
||||||
|
// ici pour que l'appelant continue de recevoir la liste complète d'un coup.
|
||||||
export const getCabineAllClients = async (): Promise<any[]> => {
|
export const getCabineAllClients = async (): Promise<any[]> => {
|
||||||
try {
|
try {
|
||||||
const { data } = await apiClient.get(`${API}/all/clients`);
|
const all: any[] = [];
|
||||||
return data.clients || [];
|
let offset = 0;
|
||||||
|
const limit = 100;
|
||||||
|
while (true) {
|
||||||
|
const { data } = await apiClient.get(`${API}/all/clients`, {
|
||||||
|
params: { limit, offset },
|
||||||
|
});
|
||||||
|
const clients = data.clients || [];
|
||||||
|
all.push(...clients);
|
||||||
|
if (!data.has_more || clients.length === 0) break;
|
||||||
|
offset += clients.length;
|
||||||
|
}
|
||||||
|
return all;
|
||||||
} catch {
|
} catch {
|
||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -31,6 +31,8 @@ export interface ClientResponse {
|
|||||||
cancellations_count: number;
|
cancellations_count: number;
|
||||||
last_penalty_reason?: string;
|
last_penalty_reason?: string;
|
||||||
referral_balance?: number;
|
referral_balance?: number;
|
||||||
|
parrain?: string | null;
|
||||||
|
rate_limited?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface CommandResponse {
|
export interface CommandResponse {
|
||||||
|
|||||||
@@ -52,8 +52,8 @@ export default function DashboardScreen() {
|
|||||||
getCommandCountByStatus("pending"),
|
getCommandCountByStatus("pending"),
|
||||||
getCommandCountByStatus("en_route"),
|
getCommandCountByStatus("en_route"),
|
||||||
getCommandCountByStatus("approved"),
|
getCommandCountByStatus("approved"),
|
||||||
getAllClients()
|
getAllClients(0, 1)
|
||||||
.then((c) => c.length)
|
.then((r) => r.total)
|
||||||
.catch(() => 0),
|
.catch(() => 0),
|
||||||
getAvailableDeliveryPersons()
|
getAvailableDeliveryPersons()
|
||||||
.then((r) => r.count)
|
.then((r) => r.count)
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ import {
|
|||||||
ActivityIndicator,
|
ActivityIndicator,
|
||||||
useWindowDimensions,
|
useWindowDimensions,
|
||||||
} from "react-native";
|
} from "react-native";
|
||||||
import { Ionicons } from "@expo/vector-icons";
|
import { Ionicons, FontAwesome5 } from "@expo/vector-icons";
|
||||||
import { spacing, fontSize, borderRadius } from "../../theme";
|
import { spacing, fontSize, borderRadius } from "../../theme";
|
||||||
import { useTheme } from "../../context/ThemeContext";
|
import { useTheme } from "../../context/ThemeContext";
|
||||||
import {
|
import {
|
||||||
@@ -24,13 +24,13 @@ import {
|
|||||||
createClientByAdmin,
|
createClientByAdmin,
|
||||||
createUserByAdmin,
|
createUserByAdmin,
|
||||||
setClientParrain,
|
setClientParrain,
|
||||||
getClientParrain,
|
|
||||||
creditClientReferral,
|
creditClientReferral,
|
||||||
resetClientReferral,
|
resetClientReferral,
|
||||||
getClientCancelledOrders,
|
getClientCancelledOrders,
|
||||||
getSettings,
|
getSettings,
|
||||||
applyClientPenalty,
|
applyClientPenalty,
|
||||||
resetClientPenalties,
|
resetClientPenalties,
|
||||||
|
resetClientRateLimit,
|
||||||
resetClientPoints,
|
resetClientPoints,
|
||||||
addClientPoints,
|
addClientPoints,
|
||||||
subtractClientPoints,
|
subtractClientPoints,
|
||||||
@@ -138,8 +138,12 @@ export default function UsersScreen() {
|
|||||||
}
|
}
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
const PAGE_SIZE = 100;
|
||||||
const [users, setUsers] = useState<UserItem[]>([]);
|
const [users, setUsers] = useState<UserItem[]>([]);
|
||||||
const [clients, setClients] = useState<ClientResponse[]>([]);
|
const [clients, setClients] = useState<ClientResponse[]>([]);
|
||||||
|
const [usersHasMore, setUsersHasMore] = useState(true);
|
||||||
|
const [clientsHasMore, setClientsHasMore] = useState(true);
|
||||||
|
const [loadingMore, setLoadingMore] = useState(false);
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
const [refreshing, setRefreshing] = useState(false);
|
const [refreshing, setRefreshing] = useState(false);
|
||||||
const [poolNames, setPoolNames] = useState<string[]>([]);
|
const [poolNames, setPoolNames] = useState<string[]>([]);
|
||||||
@@ -249,15 +253,19 @@ export default function UsersScreen() {
|
|||||||
// --------------------------------------------------
|
// --------------------------------------------------
|
||||||
// Data
|
// Data
|
||||||
// --------------------------------------------------
|
// --------------------------------------------------
|
||||||
|
// Charge la première page (100 users + 100 clients). D'autres pages sont
|
||||||
|
// chargées via loadMore() au fur et à mesure que l'utilisateur scrolle.
|
||||||
const loadData = useCallback(async () => {
|
const loadData = useCallback(async () => {
|
||||||
try {
|
try {
|
||||||
const [usersData, clientsData, settingsRes] = await Promise.all([
|
const [usersRes, clientsRes, settingsRes] = await Promise.all([
|
||||||
getAllUsers(),
|
getAllUsers(0, PAGE_SIZE),
|
||||||
getAllClients(),
|
getAllClients(0, PAGE_SIZE),
|
||||||
getSettings(),
|
getSettings(),
|
||||||
]);
|
]);
|
||||||
setUsers(usersData);
|
setUsers(usersRes.items);
|
||||||
setClients(clientsData);
|
setClients(clientsRes.items);
|
||||||
|
setUsersHasMore(usersRes.hasMore);
|
||||||
|
setClientsHasMore(clientsRes.hasMore);
|
||||||
if (settingsRes.success && settingsRes.settings) {
|
if (settingsRes.success && settingsRes.settings) {
|
||||||
const pools = settingsRes.settings.points_pools ?? [];
|
const pools = settingsRes.settings.points_pools ?? [];
|
||||||
setPoolNames(pools.map((p) => p.name));
|
setPoolNames(pools.map((p) => p.name));
|
||||||
@@ -271,33 +279,58 @@ export default function UsersScreen() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Charger le parrain de chaque client en parallèle (best-effort,
|
const map: Record<string, string | null> = {};
|
||||||
// une erreur sur un client n'empêche pas les autres de s'afficher).
|
for (const c of clientsRes.items) {
|
||||||
const clientUsernames = (clientsData ?? []).map((c) => c.username);
|
map[c.username] = c.parrain || null;
|
||||||
if (clientUsernames.length > 0) {
|
|
||||||
const results = await Promise.all(
|
|
||||||
clientUsernames.map(async (username) => {
|
|
||||||
const res = await getClientParrain(username);
|
|
||||||
return [
|
|
||||||
username,
|
|
||||||
res.success ? (res.parrain ?? null) : null,
|
|
||||||
] as const;
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
const map: Record<string, string | null> = {};
|
|
||||||
for (const [username, parrain] of results) {
|
|
||||||
map[username] = parrain;
|
|
||||||
}
|
|
||||||
setParrainMap(map);
|
|
||||||
} else {
|
|
||||||
setParrainMap({});
|
|
||||||
}
|
}
|
||||||
|
setParrainMap(map);
|
||||||
} catch {
|
} catch {
|
||||||
/* ignore */
|
/* ignore */
|
||||||
}
|
}
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
// Charge la page suivante de users/clients et l'ajoute à la liste déjà
|
||||||
|
// affichée (déclenché par le scroll de la FlatList, cf. onEndReached).
|
||||||
|
const loadMore = useCallback(async () => {
|
||||||
|
if (loadingMore || (!usersHasMore && !clientsHasMore)) return;
|
||||||
|
setLoadingMore(true);
|
||||||
|
try {
|
||||||
|
const [usersRes, clientsRes] = await Promise.all([
|
||||||
|
usersHasMore
|
||||||
|
? getAllUsers(users.length, PAGE_SIZE)
|
||||||
|
: Promise.resolve<{
|
||||||
|
items: UserItem[];
|
||||||
|
hasMore: boolean;
|
||||||
|
}>({ items: [], hasMore: false }),
|
||||||
|
clientsHasMore
|
||||||
|
? getAllClients(clients.length, PAGE_SIZE)
|
||||||
|
: Promise.resolve<{
|
||||||
|
items: ClientResponse[];
|
||||||
|
hasMore: boolean;
|
||||||
|
}>({ items: [], hasMore: false }),
|
||||||
|
]);
|
||||||
|
if (usersRes.items.length > 0) {
|
||||||
|
setUsers((prev) => [...prev, ...usersRes.items]);
|
||||||
|
}
|
||||||
|
setUsersHasMore(usersRes.hasMore);
|
||||||
|
if (clientsRes.items.length > 0) {
|
||||||
|
setClients((prev) => [...prev, ...clientsRes.items]);
|
||||||
|
setParrainMap((prev) => {
|
||||||
|
const next = { ...prev };
|
||||||
|
for (const c of clientsRes.items) {
|
||||||
|
next[c.username] = c.parrain || null;
|
||||||
|
}
|
||||||
|
return next;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
setClientsHasMore(clientsRes.hasMore);
|
||||||
|
} catch {
|
||||||
|
/* ignore, l'utilisateur peut re-scroller pour réessayer */
|
||||||
|
}
|
||||||
|
setLoadingMore(false);
|
||||||
|
}, [loadingMore, usersHasMore, clientsHasMore, users.length, clients.length]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
loadData();
|
loadData();
|
||||||
}, [loadData]);
|
}, [loadData]);
|
||||||
@@ -310,21 +343,27 @@ export default function UsersScreen() {
|
|||||||
// --------------------------------------------------
|
// --------------------------------------------------
|
||||||
// Merged & filtered list
|
// Merged & filtered list
|
||||||
// --------------------------------------------------
|
// --------------------------------------------------
|
||||||
const getMergedUsers = () => {
|
// Merge users + clients once per data change, not on every render.
|
||||||
// Build a map of client details by username
|
const allMergedUsers = useMemo(() => {
|
||||||
const clientMap = new Map<string, ClientResponse>();
|
const clientMap = new Map<string, ClientResponse>();
|
||||||
clients.forEach((c) => clientMap.set(c.username, c));
|
clients.forEach((c) => clientMap.set(c.username, c));
|
||||||
|
|
||||||
// Merge: for each user from getAllUsers, attach client details if role=client
|
const seen = new Set<string>();
|
||||||
let merged = users.map((u) => ({
|
const merged = users.map((u) => {
|
||||||
...u,
|
seen.add(u.username);
|
||||||
clientData:
|
return {
|
||||||
u.role === "client" ? clientMap.get(u.username) || null : null,
|
...u,
|
||||||
}));
|
clientData:
|
||||||
|
u.role === "client"
|
||||||
|
? clientMap.get(u.username) || null
|
||||||
|
: null,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
// Also add clients that might not be in users list
|
// Also add clients that might not be in users list
|
||||||
clients.forEach((c) => {
|
clients.forEach((c) => {
|
||||||
if (!merged.find((m) => m.username === c.username)) {
|
if (!seen.has(c.username)) {
|
||||||
|
seen.add(c.username);
|
||||||
merged.push({
|
merged.push({
|
||||||
id: c.id,
|
id: c.id,
|
||||||
username: c.username,
|
username: c.username,
|
||||||
@@ -334,6 +373,12 @@ export default function UsersScreen() {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
return merged;
|
||||||
|
}, [users, clients]);
|
||||||
|
|
||||||
|
const mergedUsers = useMemo(() => {
|
||||||
|
let merged = allMergedUsers;
|
||||||
|
|
||||||
if (filter !== "all") {
|
if (filter !== "all") {
|
||||||
merged = merged.filter((u) => u.role === filter);
|
merged = merged.filter((u) => u.role === filter);
|
||||||
}
|
}
|
||||||
@@ -355,9 +400,7 @@ export default function UsersScreen() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return merged;
|
return merged;
|
||||||
};
|
}, [allMergedUsers, filter, search]);
|
||||||
|
|
||||||
const mergedUsers = getMergedUsers();
|
|
||||||
|
|
||||||
// Stats
|
// Stats
|
||||||
const totalClients =
|
const totalClients =
|
||||||
@@ -459,7 +502,7 @@ export default function UsersScreen() {
|
|||||||
// --------------------------------------------------
|
// --------------------------------------------------
|
||||||
// Delete user/client
|
// Delete user/client
|
||||||
// --------------------------------------------------
|
// --------------------------------------------------
|
||||||
const handleDelete = (item: ReturnType<typeof getMergedUsers>[0]) => {
|
const handleDelete = (item: (typeof allMergedUsers)[number]) => {
|
||||||
const label =
|
const label =
|
||||||
item.role === "client"
|
item.role === "client"
|
||||||
? "client"
|
? "client"
|
||||||
@@ -592,6 +635,32 @@ export default function UsersScreen() {
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const handleResetRateLimit = (client: ClientResponse) => {
|
||||||
|
showConfirm(
|
||||||
|
"Lever le rate limit",
|
||||||
|
`Débloquer "${client.username}" ? Ses compteurs de requêtes, d'annulations et de modifications d'adresse seront remis à zéro.`,
|
||||||
|
async () => {
|
||||||
|
const res = await resetClientRateLimit(client.username);
|
||||||
|
if (!res.success) {
|
||||||
|
showError("Erreur", res.error || "Echec");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setClients((prev) =>
|
||||||
|
prev.map((c) =>
|
||||||
|
c.username === client.username
|
||||||
|
? { ...c, rate_limited: false }
|
||||||
|
: c,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
showSuccess(
|
||||||
|
"Validé",
|
||||||
|
`Rate limit levé pour "${client.username}"`,
|
||||||
|
);
|
||||||
|
},
|
||||||
|
"Débloquer",
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
const handleResetAmende = () => {
|
const handleResetAmende = () => {
|
||||||
if (!sanctionModal.client) return;
|
if (!sanctionModal.client) return;
|
||||||
showConfirm(
|
showConfirm(
|
||||||
@@ -844,10 +913,16 @@ export default function UsersScreen() {
|
|||||||
if (!e.response) {
|
if (!e.response) {
|
||||||
try {
|
try {
|
||||||
if (createType === "client") {
|
if (createType === "client") {
|
||||||
const freshClients = await getAllClients();
|
// Trié par created_at DESC : un client qui vient
|
||||||
setClients(freshClients);
|
// d'être créé est forcément sur la première page.
|
||||||
|
const freshClients = await getAllClients(
|
||||||
|
0,
|
||||||
|
PAGE_SIZE,
|
||||||
|
);
|
||||||
|
setClients(freshClients.items);
|
||||||
|
setClientsHasMore(freshClients.hasMore);
|
||||||
if (
|
if (
|
||||||
freshClients.find(
|
freshClients.items.find(
|
||||||
(c) => c.username === usernameToCreate,
|
(c) => c.username === usernameToCreate,
|
||||||
)
|
)
|
||||||
) {
|
) {
|
||||||
@@ -855,11 +930,12 @@ export default function UsersScreen() {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
const freshUsers = await getAllUsers();
|
const freshUsers = await getAllUsers(0, PAGE_SIZE);
|
||||||
setUsers(freshUsers);
|
setUsers(freshUsers.items);
|
||||||
|
setUsersHasMore(freshUsers.hasMore);
|
||||||
if (
|
if (
|
||||||
freshUsers.find(
|
freshUsers.items.find(
|
||||||
(u: any) => u.username === usernameToCreate,
|
(u) => u.username === usernameToCreate,
|
||||||
)
|
)
|
||||||
) {
|
) {
|
||||||
setCreateModal(false);
|
setCreateModal(false);
|
||||||
@@ -1084,6 +1160,23 @@ export default function UsersScreen() {
|
|||||||
fontSize: fontSize.sm,
|
fontSize: fontSize.sm,
|
||||||
fontWeight: "600",
|
fontWeight: "600",
|
||||||
},
|
},
|
||||||
|
rateLimitBtn: {
|
||||||
|
flexDirection: "row",
|
||||||
|
alignItems: "center",
|
||||||
|
justifyContent: "center",
|
||||||
|
gap: spacing.xs,
|
||||||
|
marginTop: spacing.m,
|
||||||
|
paddingVertical: spacing.s,
|
||||||
|
borderRadius: borderRadius.md,
|
||||||
|
borderWidth: 1,
|
||||||
|
borderColor: colors.warning,
|
||||||
|
backgroundColor: colors.warning + "15",
|
||||||
|
},
|
||||||
|
rateLimitBtnText: {
|
||||||
|
color: colors.warning,
|
||||||
|
fontSize: fontSize.sm,
|
||||||
|
fontWeight: "600",
|
||||||
|
},
|
||||||
}),
|
}),
|
||||||
[colors, screenWidth],
|
[colors, screenWidth],
|
||||||
);
|
);
|
||||||
@@ -1094,7 +1187,7 @@ export default function UsersScreen() {
|
|||||||
const renderUser = ({
|
const renderUser = ({
|
||||||
item,
|
item,
|
||||||
}: {
|
}: {
|
||||||
item: ReturnType<typeof getMergedUsers>[0];
|
item: (typeof allMergedUsers)[number];
|
||||||
}) => {
|
}) => {
|
||||||
const isClient = item.role === "client" && item.clientData;
|
const isClient = item.role === "client" && item.clientData;
|
||||||
const roleColor = getRoleBadgeColor(item.role);
|
const roleColor = getRoleBadgeColor(item.role);
|
||||||
@@ -1395,6 +1488,24 @@ export default function UsersScreen() {
|
|||||||
</View>
|
</View>
|
||||||
)}
|
)}
|
||||||
</View>
|
</View>
|
||||||
|
{item.clientData.rate_limited && (
|
||||||
|
<TouchableOpacity
|
||||||
|
style={styles.rateLimitBtn}
|
||||||
|
onPress={() =>
|
||||||
|
handleResetRateLimit(item.clientData!)
|
||||||
|
}
|
||||||
|
activeOpacity={0.7}
|
||||||
|
>
|
||||||
|
<FontAwesome5
|
||||||
|
name="unlock"
|
||||||
|
size={14}
|
||||||
|
color={colors.warning}
|
||||||
|
/>
|
||||||
|
<Text style={styles.rateLimitBtnText}>
|
||||||
|
Rate limité — Débloquer
|
||||||
|
</Text>
|
||||||
|
</TouchableOpacity>
|
||||||
|
)}
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
@@ -1515,6 +1626,8 @@ export default function UsersScreen() {
|
|||||||
data={mergedUsers}
|
data={mergedUsers}
|
||||||
keyExtractor={(item) => `${item.role}-${item.id}`}
|
keyExtractor={(item) => `${item.role}-${item.id}`}
|
||||||
renderItem={renderUser}
|
renderItem={renderUser}
|
||||||
|
onEndReached={loadMore}
|
||||||
|
onEndReachedThreshold={0.5}
|
||||||
refreshControl={
|
refreshControl={
|
||||||
<RefreshControl
|
<RefreshControl
|
||||||
refreshing={refreshing}
|
refreshing={refreshing}
|
||||||
@@ -1529,6 +1642,14 @@ export default function UsersScreen() {
|
|||||||
ListEmptyComponent={
|
ListEmptyComponent={
|
||||||
<Text style={styles.empty}>Aucun utilisateur</Text>
|
<Text style={styles.empty}>Aucun utilisateur</Text>
|
||||||
}
|
}
|
||||||
|
ListFooterComponent={
|
||||||
|
loadingMore ? (
|
||||||
|
<ActivityIndicator
|
||||||
|
color={colors.accent}
|
||||||
|
style={{ marginVertical: spacing.l }}
|
||||||
|
/>
|
||||||
|
) : null
|
||||||
|
}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
{/* Edit client modal */}
|
{/* Edit client modal */}
|
||||||
|
|||||||
Reference in New Issue
Block a user