chore: build
This commit is contained in:
@@ -76,8 +76,9 @@ func (d *Database) GetClientByID(id int) (*models.Client, error) {
|
||||
return client, nil
|
||||
}
|
||||
|
||||
// GetAllClients récupère tous les clients
|
||||
func (d *Database) GetAllClients() ([]*models.Client, error) {
|
||||
// GetAllClients récupère une page de clients, triée par date de création
|
||||
// descendante, ainsi que le nombre total de clients en base.
|
||||
func (d *Database) GetAllClients(limit, offset int) ([]*models.Client, int64, error) {
|
||||
var rows []struct {
|
||||
ID int `gorm:"column:id"`
|
||||
Username string `gorm:"column:username"`
|
||||
@@ -89,16 +90,25 @@ func (d *Database) GetAllClients() ([]*models.Client, error) {
|
||||
Amende float64 `gorm:"column:amende"`
|
||||
ReferralBalance float64 `gorm:"column:referral_balance"`
|
||||
CancellationsCount int `gorm:"column:cancellations_count"`
|
||||
LastPenaltyReason string `gorm:"column:last_penalty_reason"`
|
||||
Parrain string `gorm:"column:parrain"`
|
||||
PointsExtraJSON []byte `gorm:"column:points_extra"`
|
||||
CreatedAt time.Time `gorm:"column:created_at"`
|
||||
}
|
||||
err := d.GDB.Raw(`
|
||||
SELECT id, username, password, nom, prenom, telephone, command, amende, referral_balance,
|
||||
COALESCE(cancellations_count, 0) as cancellations_count,
|
||||
COALESCE(last_penalty_reason, '') as last_penalty_reason,
|
||||
COALESCE(parrain, '') as parrain,
|
||||
COALESCE(points_extra, '{}'::jsonb) as points_extra, created_at
|
||||
FROM clients ORDER BY created_at DESC`).Scan(&rows).Error
|
||||
FROM clients ORDER BY created_at DESC LIMIT ? OFFSET ?`, limit, offset).Scan(&rows).Error
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("erreur lors de la récupération des clients: %w", err)
|
||||
return nil, 0, fmt.Errorf("erreur lors de la récupération des clients: %w", err)
|
||||
}
|
||||
|
||||
var total int64
|
||||
if err := d.GDB.Table("clients").Count(&total).Error; err != nil {
|
||||
return nil, 0, fmt.Errorf("erreur lors du comptage des clients: %w", err)
|
||||
}
|
||||
|
||||
clients := make([]*models.Client, 0, len(rows))
|
||||
@@ -114,6 +124,8 @@ func (d *Database) GetAllClients() ([]*models.Client, error) {
|
||||
Amende: row.Amende,
|
||||
ReferralBalance: row.ReferralBalance,
|
||||
CancellationsCount: row.CancellationsCount,
|
||||
LastPenaltyReason: row.LastPenaltyReason,
|
||||
Parrain: row.Parrain,
|
||||
CreatedAt: row.CreatedAt,
|
||||
}
|
||||
client.PointsExtra = map[string]int{}
|
||||
@@ -123,7 +135,7 @@ func (d *Database) GetAllClients() ([]*models.Client, error) {
|
||||
clients = append(clients, client)
|
||||
}
|
||||
|
||||
return clients, nil
|
||||
return clients, total, nil
|
||||
}
|
||||
|
||||
// UpdateClient met à jour un client existant
|
||||
|
||||
@@ -6,10 +6,13 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
var allowedStatuses = map[string]bool{
|
||||
@@ -98,6 +101,138 @@ func ValidateStatuses(statuses string) ([]string, error) {
|
||||
return cleanStatuses, nil
|
||||
}
|
||||
|
||||
// DeliveryPersonDetails regroupe les infos enrichies d'un livreur pour un
|
||||
// affichage en liste (statut, position, queue, compteurs de livraisons).
|
||||
type DeliveryPersonDetails struct {
|
||||
Status string
|
||||
HasLocation bool
|
||||
Latitude float64
|
||||
Longitude float64
|
||||
LocationLastUpdate int64
|
||||
QueueSize int
|
||||
CurrentCommand int
|
||||
TotalDeliveries int
|
||||
CompletedDeliveries int
|
||||
PendingDeliveries int
|
||||
}
|
||||
|
||||
// GetDeliveryPersonsDetailsBatch récupère les infos enrichies de plusieurs
|
||||
// livreurs en quelques allers-retours Redis/DB au lieu d'une requête
|
||||
// complète par livreur (l'ancien pattern faisait ~6-8 requêtes par livreur :
|
||||
// GetUserByUsername + 2 lectures Redis + GetDeliverymanQueueSize +
|
||||
// GetCurrentCommand + 3 COUNT(*) séparés, répété pour chaque livreur de la
|
||||
// liste — coûteux dès que ces écrans sont rafraîchis en polling).
|
||||
func (d *Database) GetDeliveryPersonsDetailsBatch(usernames []string) map[string]*DeliveryPersonDetails {
|
||||
result := make(map[string]*DeliveryPersonDetails, len(usernames))
|
||||
for _, u := range usernames {
|
||||
result[u] = &DeliveryPersonDetails{Status: "offline"}
|
||||
}
|
||||
if len(usernames) == 0 {
|
||||
return result
|
||||
}
|
||||
|
||||
statusKeys := make([]string, len(usernames))
|
||||
currentKeys := make([]string, len(usernames))
|
||||
locationKeys := make([]string, len(usernames))
|
||||
for i, u := range usernames {
|
||||
statusKeys[i] = fmt.Sprintf("delivery:status:%s", u)
|
||||
currentKeys[i] = fmt.Sprintf("delivery:current:%s", u)
|
||||
locationKeys[i] = fmt.Sprintf("delivery:location:%s", u)
|
||||
}
|
||||
|
||||
// MGET regroupe la lecture de toutes les clés d'un type en un seul
|
||||
// aller-retour Redis, quel que soit le nombre de livreurs.
|
||||
if statuses, err := Redis.MGet(RedisCtx, statusKeys...).Result(); err == nil {
|
||||
for i, v := range statuses {
|
||||
if s, ok := v.(string); ok && s != "" {
|
||||
result[usernames[i]].Status = s
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if currents, err := Redis.MGet(RedisCtx, currentKeys...).Result(); err == nil {
|
||||
for i, v := range currents {
|
||||
s, ok := v.(string)
|
||||
if !ok || s == "" {
|
||||
continue
|
||||
}
|
||||
var id int
|
||||
if _, err := fmt.Sscanf(s, "%d", &id); err == nil {
|
||||
result[usernames[i]].CurrentCommand = id
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if locations, err := Redis.MGet(RedisCtx, locationKeys...).Result(); err == nil {
|
||||
for i, v := range locations {
|
||||
s, ok := v.(string)
|
||||
if !ok || s == "" {
|
||||
continue
|
||||
}
|
||||
var loc struct {
|
||||
Latitude float64 `json:"latitude"`
|
||||
Longitude float64 `json:"longitude"`
|
||||
LastUpdate int64 `json:"last_update"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(s), &loc); err == nil {
|
||||
det := result[usernames[i]]
|
||||
det.HasLocation = true
|
||||
det.Latitude = loc.Latitude
|
||||
det.Longitude = loc.Longitude
|
||||
det.LocationLastUpdate = loc.LastUpdate
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// LLEN ne se groupe pas via MGET (ce n'est pas une clé string) : un
|
||||
// pipeline permet quand même de n'envoyer qu'un seul aller-retour réseau
|
||||
// pour les N commandes LLEN.
|
||||
pipe := Redis.Pipeline()
|
||||
queueCmds := make([]*redis.IntCmd, len(usernames))
|
||||
for i, u := range usernames {
|
||||
queueCmds[i] = pipe.LLen(RedisCtx, fmt.Sprintf("delivery:queue:%s", u))
|
||||
}
|
||||
if _, err := pipe.Exec(RedisCtx); err == nil {
|
||||
for i, cmd := range queueCmds {
|
||||
if n, err := cmd.Result(); err == nil {
|
||||
result[usernames[i]].QueueSize = int(n)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Les 3 COUNT(*) par livreur (total / terminées / en cours) deviennent
|
||||
// une seule requête groupée par livreur_assign pour tous à la fois.
|
||||
type countRow struct {
|
||||
Livreur string `gorm:"column:livreur_assign"`
|
||||
Total int `gorm:"column:total"`
|
||||
Completed int `gorm:"column:completed"`
|
||||
Pending int `gorm:"column:pending"`
|
||||
}
|
||||
var rows []countRow
|
||||
err := d.GDB.Raw(`
|
||||
SELECT livreur_assign,
|
||||
COUNT(*) AS total,
|
||||
COUNT(*) FILTER (WHERE status = 'approved') AS completed,
|
||||
COUNT(*) FILTER (WHERE status IN ('assigned', 'en_route', 'livre')) AS pending
|
||||
FROM commandes
|
||||
WHERE livreur_assign IN ?
|
||||
GROUP BY livreur_assign`, usernames,
|
||||
).Scan(&rows).Error
|
||||
if err != nil {
|
||||
log.Printf("❌ [GetDeliveryPersonsDetailsBatch] Erreur comptage: %v", err)
|
||||
} else {
|
||||
for _, r := range rows {
|
||||
if det, ok := result[r.Livreur]; ok {
|
||||
det.TotalDeliveries = r.Total
|
||||
det.CompletedDeliveries = r.Completed
|
||||
det.PendingDeliveries = r.Pending
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
// GetLastDeliveryDate récupère la date de la dernière livraison d'un livreur
|
||||
func (d *Database) GetLastDeliveryDate(livreurUsername string) (*time.Time, error) {
|
||||
var result struct {
|
||||
|
||||
@@ -538,6 +538,8 @@ func (db *Database) createTables() error {
|
||||
`CREATE INDEX IF NOT EXISTS idx_jwt_date_fin ON jwt_tokens(date_fin);`,
|
||||
`CREATE INDEX IF NOT EXISTS idx_clients_telephone ON clients(telephone);`,
|
||||
`CREATE INDEX IF NOT EXISTS idx_clients_cancellations ON clients(cancellations_count);`,
|
||||
`CREATE INDEX IF NOT EXISTS idx_clients_created_at ON clients(created_at DESC);`,
|
||||
`CREATE INDEX IF NOT EXISTS idx_users_created_at ON users(created_at DESC);`,
|
||||
`CREATE INDEX IF NOT EXISTS idx_clients_amende ON clients(amende) WHERE amende > 0;`,
|
||||
`CREATE INDEX IF NOT EXISTS idx_cmd_username ON commandes(username);`,
|
||||
`CREATE INDEX IF NOT EXISTS idx_cmd_status ON commandes(status);`,
|
||||
|
||||
@@ -13,12 +13,16 @@ func (d *Database) CreateUser(user *models.User) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *Database) GetAllUsers() ([]*models.User, error) {
|
||||
func (d *Database) GetAllUsers(limit, offset int) ([]*models.User, int64, error) {
|
||||
var users []*models.User
|
||||
if err := d.GDB.Order("created_at DESC").Limit(500).Find(&users).Error; err != nil {
|
||||
return nil, fmt.Errorf("erreur lors de la récupération des utilisateurs: %w", err)
|
||||
if err := d.GDB.Order("created_at DESC").Limit(limit).Offset(offset).Find(&users).Error; err != nil {
|
||||
return nil, 0, fmt.Errorf("erreur lors de la récupération des utilisateurs: %w", err)
|
||||
}
|
||||
return users, nil
|
||||
var total int64
|
||||
if err := d.GDB.Model(&models.User{}).Count(&total).Error; err != nil {
|
||||
return nil, 0, fmt.Errorf("erreur lors du comptage des utilisateurs: %w", err)
|
||||
}
|
||||
return users, total, nil
|
||||
}
|
||||
|
||||
func (d *Database) GetAllDeliveryMen() ([]*models.User, error) {
|
||||
|
||||
Reference in New Issue
Block a user