From ae89d995d2343e4fd4be9a5ec6faa0da35f2dd7f Mon Sep 17 00:00:00 2001 From: Cameron Foussard Date: Tue, 3 Nov 2026 09:12:36 +0100 Subject: [PATCH] chore: build --- backend/gestion/db/db_users.go | 33 +++++++++++++++++++ backend/gestion/handlers/auth.go | 15 +++++++-- frontend-admin/src/api/api_admin.ts | 12 ++++++- .../src/screens/admin/DashboardScreen.tsx | 24 +++++++++++--- .../src/screens/admin/UsersScreen.tsx | 29 ++++++++++++---- 5 files changed, 98 insertions(+), 15 deletions(-) diff --git a/backend/gestion/db/db_users.go b/backend/gestion/db/db_users.go index a99c0f54..e52a5864 100644 --- a/backend/gestion/db/db_users.go +++ b/backend/gestion/db/db_users.go @@ -25,6 +25,39 @@ func (d *Database) GetAllUsers(limit, offset int) ([]*models.User, int64, error) return users, total, nil } +// UserCounts contient les totaux globaux (non paginés) affichés côté admin. +// Les usernames présents à la fois dans users et clients ne sont comptés +// qu'une fois, comme dans la liste fusionnée du front. +type UserCounts struct { + All int64 `json:"all" gorm:"column:all_count"` + Client int64 `json:"client" gorm:"column:client_count"` + Livreur int64 `json:"livreur" gorm:"column:livreur_count"` + Cabine int64 `json:"cabine" gorm:"column:cabine_count"` + Admin int64 `json:"admin" gorm:"column:admin_count"` +} + +func (d *Database) GetUserCounts() (*UserCounts, error) { + var counts UserCounts + err := d.GDB.Raw(` + WITH merged AS ( + SELECT username, role FROM users + UNION + SELECT c.username, 'client' AS role FROM clients c + WHERE NOT EXISTS (SELECT 1 FROM users u WHERE u.username = c.username) + ) + SELECT + COUNT(DISTINCT username) AS all_count, + COUNT(DISTINCT username) FILTER (WHERE role = 'client') AS client_count, + COUNT(DISTINCT username) FILTER (WHERE role = 'livreur') AS livreur_count, + COUNT(DISTINCT username) FILTER (WHERE role = 'cabine') AS cabine_count, + COUNT(DISTINCT username) FILTER (WHERE role = 'admin') AS admin_count + FROM merged`).Scan(&counts).Error + if err != nil { + return nil, fmt.Errorf("erreur lors du comptage des utilisateurs par rôle: %w", err) + } + return &counts, nil +} + func (d *Database) GetAllDeliveryMen() ([]*models.User, error) { var users []*models.User if err := d.GDB.Where("role = ?", "livreur").Limit(100).Find(&users).Error; err != nil { diff --git a/backend/gestion/handlers/auth.go b/backend/gestion/handlers/auth.go index 23bd160e..70428bb3 100644 --- a/backend/gestion/handlers/auth.go +++ b/backend/gestion/handlers/auth.go @@ -544,11 +544,22 @@ func GetAllUsers(c *gin.Context) { 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{ + resp := gin.H{ "users": sanitized, "count": total, "has_more": int64(offset+len(users)) < total, - }) + } + // Totaux globaux par rôle (indépendants de la pagination) : uniquement + // sur la première page, c'est là que le front les lit. + if offset == 0 { + if counts, err := database.GetUserCounts(); err != nil { + log.Printf("⚠️ [GET_ALL_USERS] Comptage par rôle impossible: %v", err) + } else { + resp["counts"] = counts + } + } + + c.JSON(http.StatusOK, resp) } func GetAllDeliveryMen(c *gin.Context) { diff --git a/frontend-admin/src/api/api_admin.ts b/frontend-admin/src/api/api_admin.ts index c0c5b6f7..db653f47 100644 --- a/frontend-admin/src/api/api_admin.ts +++ b/frontend-admin/src/api/api_admin.ts @@ -233,10 +233,19 @@ export const getAllClients = async ( }; }; +// Totaux globaux (toute la base, pas seulement la page chargée). +export interface UserCounts { + all: number; + client: number; + livreur: number; + cabine: number; + admin: number; +} + export const getAllUsers = async ( offset = 0, limit = 100, -): Promise> => { +): Promise & { counts?: UserCounts }> => { const { data } = await apiClient.get(`${V2}/admin/protected/all/users`, { params: { limit, offset }, }); @@ -244,6 +253,7 @@ export const getAllUsers = async ( items: data.users || [], total: data.count ?? 0, hasMore: !!data.has_more, + counts: data.counts ?? undefined, }; }; diff --git a/frontend-admin/src/screens/admin/DashboardScreen.tsx b/frontend-admin/src/screens/admin/DashboardScreen.tsx index 2429483c..9662f599 100644 --- a/frontend-admin/src/screens/admin/DashboardScreen.tsx +++ b/frontend-admin/src/screens/admin/DashboardScreen.tsx @@ -18,6 +18,7 @@ import { useAuth } from "../../auth/AuthContext"; import { getAllCommands, getAllClients, + getAllUsers, getAvailableDeliveryPersons, getCommandCountByStatus, getAdminTelegramStatus, @@ -46,15 +47,22 @@ export default function DashboardScreen() { const loadStats = useCallback(async () => { try { - const [allCmd, pending, enRoute, completed, clients, livreurs] = + const [allCmd, pending, enRoute, completed, userCounts, livreurs] = await Promise.all([ getAllCommands().then((r) => r.count), getCommandCountByStatus("pending"), getCommandCountByStatus("en_route"), getCommandCountByStatus("approved"), - getAllClients(0, 1) - .then((r) => r.total) - .catch(() => 0), + // Totaux globaux (toute la base) : on ne charge qu'1 user, + // seuls les compteurs nous intéressent. + getAllUsers(0, 1) + .then(async (r) => ({ + all: r.counts?.all ?? r.total, + client: + r.counts?.client ?? + (await getAllClients(0, 1)).total, + })) + .catch(() => ({ all: 0, client: 0 })), getAvailableDeliveryPersons() .then((r) => r.count) .catch(() => 0), @@ -85,9 +93,15 @@ export default function DashboardScreen() { icon: "checkmark-circle-outline", color: colors.success, }, + { + label: "Utilisateurs", + value: userCounts.all, + icon: "person-outline", + color: colors.accent, + }, { label: "Clients", - value: clients, + value: userCounts.client, icon: "people-outline", color: colors.accentLight, }, diff --git a/frontend-admin/src/screens/admin/UsersScreen.tsx b/frontend-admin/src/screens/admin/UsersScreen.tsx index f79c3641..fef59174 100644 --- a/frontend-admin/src/screens/admin/UsersScreen.tsx +++ b/frontend-admin/src/screens/admin/UsersScreen.tsx @@ -36,7 +36,11 @@ import { subtractClientPoints, getLivreurLoginHistory, } from "../../api/api_admin"; -import type { CancelledOrder, LoginHistoryWeek } from "../../api/api_admin"; +import type { + CancelledOrder, + LoginHistoryWeek, + UserCounts, +} from "../../api/api_admin"; import type { ClientResponse } from "../../api/types"; import LoadingSpinner from "../../components/ui/LoadingSpinner"; import Card from "../../components/ui/Card"; @@ -144,6 +148,9 @@ export default function UsersScreen() { const [usersHasMore, setUsersHasMore] = useState(true); const [clientsHasMore, setClientsHasMore] = useState(true); const [loadingMore, setLoadingMore] = useState(false); + // Totaux globaux renvoyés par le backend (toute la base, pas seulement + // les pages déjà chargées). + const [counts, setCounts] = useState(null); const [loading, setLoading] = useState(true); const [refreshing, setRefreshing] = useState(false); const [poolNames, setPoolNames] = useState([]); @@ -264,6 +271,7 @@ export default function UsersScreen() { ]); setUsers(usersRes.items); setClients(clientsRes.items); + if (usersRes.counts) setCounts(usersRes.counts); setUsersHasMore(usersRes.hasMore); setClientsHasMore(clientsRes.hasMore); if (settingsRes.success && settingsRes.settings) { @@ -402,15 +410,21 @@ export default function UsersScreen() { return merged; }, [allMergedUsers, filter, search]); - // Stats + // Stats : totaux globaux du backend. Repli sur les données chargées + // uniquement si le backend n'a pas renvoyé les totaux. + const totalAll = counts?.all ?? allMergedUsers.length; const totalClients = - users.filter((u) => u.role === "client").length || clients.length; - const totalLivreurs = users.filter((u) => u.role === "livreur").length; - const totalCabines = users.filter((u) => u.role === "cabine").length; - const totalAdmins = users.filter((u) => u.role === "admin").length; + counts?.client ?? + (users.filter((u) => u.role === "client").length || clients.length); + const totalLivreurs = + counts?.livreur ?? users.filter((u) => u.role === "livreur").length; + const totalCabines = + counts?.cabine ?? users.filter((u) => u.role === "cabine").length; + const totalAdmins = + counts?.admin ?? users.filter((u) => u.role === "admin").length; const getCountForFilter = (f: RoleFilter) => { - if (f === "all") return mergedUsers.length; + if (f === "all") return totalAll; if (f === "client") return totalClients; if (f === "livreur") return totalLivreurs; if (f === "cabine") return totalCabines; @@ -933,6 +947,7 @@ export default function UsersScreen() { const freshUsers = await getAllUsers(0, PAGE_SIZE); setUsers(freshUsers.items); setUsersHasMore(freshUsers.hasMore); + if (freshUsers.counts) setCounts(freshUsers.counts); if ( freshUsers.items.find( (u) => u.username === usernameToCreate,