Improve user data retrieval and add production debugging tools

Update the API to fetch users with simplified logic and introduce detailed SQL scripts and logging for production issue diagnosis.

Replit-Commit-Author: Agent
Replit-Commit-Session-Id: a8a78c07-e900-425c-a577-5b4c5894379d
Replit-Commit-Checkpoint-Type: full_checkpoint
Replit-Commit-Screenshot-Url: https://storage.googleapis.com/screenshot-production-us-central1/1957c339-2757-4d1f-8e92-e9f71a1ce58e/a8a78c07-e900-425c-a577-5b4c5894379d/jzCmXCx
This commit is contained in:
michaelschal committed 2025-08-11 20:00:10 +00:00
1 parent 22bdbff494
commit 7235be8b84
4 files changed
+91 -20

No files matched your search

+21 -11
View File
@@ -34,18 +34,28 @@ ADD COLUMN IF NOT EXISTS created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP;
## Débogage Production
### Script de Diagnostic SQL
Utilisez le script `debug-usergroups-production.sql` pour :
- Vérifier la structure de la table user_groups
- Examiner les données existantes
- Identifier les problèmes d'association utilisateur-groupe
### Problème "Aucun utilisateur trouvé"
Si l'interface affiche "Aucun utilisateur trouvé" :
### Logs de Débogage
Les logs suivants sont maintenant disponibles :
- `🔍 getUserWithGroups called for user: [id]`
- `🔍 Querying user_groups for user: [id]`
- `🔍 Found X group assignments for user [id]`
- `⚠️ Production mode: user_groups table missing created_at column, using raw SQL`
1. **Vérification Base de Données** : Utilisez `production-users-debug.sql`
```bash
psql $DATABASE_URL -f production-users-debug.sql
```
2. **Vérification API** : Testez l'endpoint directement
```bash
curl -H "Cookie: [votre-cookie-session]" https://votre-domaine.com/api/users
```
### Script de Diagnostic SQL
- `debug-usergroups-production.sql` : Problèmes d'association utilisateur-groupe
- `production-users-debug.sql` : Problème de récupération des utilisateurs
### Logs de Débogage Disponibles
- `🔍 GET /api/users - Fetching users with simplified approach`
- `📊 Found X base users`
- `❌ Error getting groups for user [username]:`
- `🔐 API /api/users - Returning: {length: X, totalGroups: Y}`
## Déploiement
Binary file not shown.

After

Width:  |  Height:  |  Size: 171 KiB

+37
View File
@@ -0,0 +1,37 @@
-- Script de diagnostic pour résoudre le problème "Aucun utilisateur trouvé" en production
-- 1. Vérifier si la table users existe et contient des données
SELECT 'Users table check' as diagnostic;
SELECT COUNT(*) as user_count FROM users;
SELECT id, username, email, role FROM users LIMIT 5;
-- 2. Vérifier la structure de la table users
SELECT 'Users table structure' as diagnostic;
\d users;
-- 3. Vérifier les connexions/permissions de base de données
SELECT 'Database info' as diagnostic;
SELECT current_database(), current_user, version();
-- 4. Vérifier la table groups
SELECT 'Groups table check' as diagnostic;
SELECT COUNT(*) as group_count FROM groups;
SELECT id, name FROM groups LIMIT 5;
-- 5. Vérifier la table user_groups et sa structure
SELECT 'User_groups table check' as diagnostic;
SELECT COUNT(*) as user_group_count FROM user_groups;
\d user_groups;
-- 6. Test de la requête utilisée par l'application
SELECT 'Full user query test' as diagnostic;
SELECT
u.id,
u.username,
u.email,
u.role,
COUNT(ug.group_id) as groups_count
FROM users u
LEFT JOIN user_groups ug ON u.id = ug.user_id
GROUP BY u.id, u.username, u.email, u.role
LIMIT 5;
+33 -9
View File
@@ -862,20 +862,44 @@ export async function registerRoutes(app: Express): Promise<Server> {
return res.status(403).json({ message: "Access denied" });
}
console.log('🔍 GET /api/users - Fetching users with roles and groups');
// Get all users with groups for admin
const allUsers = await storage.getUsersWithRolesAndGroups();
const safeUsers = Array.isArray(allUsers) ? allUsers : [];
console.log('🔍 GET /api/users - Fetching users with simplified approach');
// Get all basic users first
const baseUsers = await storage.getUsers();
console.log(`📊 Found ${baseUsers.length} base users`);
// Add userGroups and userRoles to each user individually with error handling
const usersWithData = await Promise.all(
baseUsers.map(async (baseUser) => {
try {
const userWithGroups = await storage.getUserWithGroups(baseUser.id);
return {
...baseUser,
userGroups: userWithGroups?.userGroups || [],
userRoles: [] // Keep roles simple for now since we're using hardcoded permissions
};
} catch (error) {
console.error(`❌ Error getting groups for user ${baseUser.username}:`, error);
// Return user with empty groups if there's an error
return {
...baseUser,
userGroups: [],
userRoles: []
};
}
})
);
console.log('🔐 API /api/users - Returning:', {
isArray: Array.isArray(safeUsers),
length: safeUsers.length,
firstUserGroups: safeUsers.length > 0 ? safeUsers[0].userGroups?.length || 0 : 0
isArray: Array.isArray(usersWithData),
length: usersWithData.length,
totalGroups: usersWithData.reduce((sum, u) => sum + (u.userGroups?.length || 0), 0)
});
res.json(safeUsers);
res.json(usersWithData);
} catch (error) {
console.error("Error fetching users:", error);
console.error("❌ Critical error fetching users:", error);
console.error("❌ Error stack:", error.stack);
// En cas d'erreur, retourner un array vide pour éviter React Error #310
res.status(500).json([]);
}