diff --git a/DLC-PRODUCTION-FIX-FINAL.md b/DLC-PRODUCTION-FIX-FINAL.md index 32e5616..9ad48ea 100644 --- a/DLC-PRODUCTION-FIX-FINAL.md +++ b/DLC-PRODUCTION-FIX-FINAL.md @@ -1,95 +1,81 @@ -# Fix Final DLC Production - Employee Magasin #2 → Magasin #1 +# Fix Final Production - Problème UserGroups -## Problème Identifié +## Problème Identifié en Production -**EXACT** : Employé magasin #2 crée DLC → apparaît dans magasin #1 +Les logs frontend montraient : +```javascript +Customer Order Frontend Debug: { + userRole: 'employee', + selectedStoreId: 1, + userGroups: undefined, // ❌ PROBLÈME ICI ! + initialGroupId: undefined, + availableGroups: [...] +} +Final groupId selected: 1 // ❌ Fallback utilisé au lieu du groupe assigné +``` ## Cause Racine Trouvée +### ✅ Backend fonctionne correctement +- `storage.getUserWithGroups(id)` retourne bien les groupes +- `passport.deserializeUser` charge les `userGroups` + +### ❌ Route `/api/user` manquait userGroups ```javascript -// Erreur de validation backend: -{"message":"Validation error","errors":[{"code":"invalid_type","expected":"number","received":"undefined","path":["groupId"],"message":"Required"}]} -``` +// AVANT (Production cassée) +app.get("/api/user", (req: any, res) => { + res.json({ + id: req.user.id, + role: req.user.role, + // userGroups: MANQUANT ! ❌ + }); +}); -**CAUSE** : Frontend ne transmet pas `groupId` dans la requête → Backend validation échoue -**CONSÉQUENCE** : DLC pas créée OU créée avec mauvais groupId par défaut - -## Solutions Appliquées - -### 1. Fix Backend - Force GroupId Assignment -**Fichier:** `server/routes.ts` ligne 2325-2335 - -```javascript -// Fix groupId if missing - use user's assigned group or fallback -let finalGroupId = req.body.groupId; -if (!finalGroupId) { - if (user.userGroups?.[0]?.groupId) { - finalGroupId = user.userGroups[0].groupId; - console.log("🔧 Backend Fix: Using user's assigned group:", finalGroupId); - } else { - finalGroupId = 1; // Emergency fallback - console.log("🚨 Backend Fix: Using emergency fallback groupId:", finalGroupId); - } -} -``` - -### 2. Frontend DLC Logic Déjà Corrigée -**Fichier:** `client/src/pages/DlcPage.tsx` ligne 201-234 - -```javascript -// Déterminer le groupId correctement selon le rôle utilisateur -let groupId; -if (user?.role === 'admin' && selectedStoreId) { - groupId = selectedStoreId; -} else if (user?.userGroups?.[0]?.groupId) { - // UTILISATEUR NON-ADMIN: utiliser son groupe assigné ✅ - groupId = user.userGroups[0].groupId; -} else if (user?.role === 'admin') { - groupId = stores[0]?.id || 1; -} else { - groupId = 1; // Fallback par défaut -} -``` - -### 3. Debug Logs Production -```javascript -console.log("🏪 DLC GroupId Selection DEBUG:", { - userRole: user?.role, - selectedStoreId, - userGroups: user?.userGroups?.map(ug => ({groupId: ug.groupId, groupName: ug.group?.name})), - availableStores: stores.map(s => ({id: s.id, name: s.name})), - userGroupsRaw: user?.userGroups, - firstUserGroup: user?.userGroups?.[0], - finalGroupId: groupId, - logicPath: !groupId ? 'need-fallback' : 'already-set' +// APRÈS (Production fixée) +app.get("/api/user", (req: any, res) => { + res.json({ + id: req.user.id, + role: req.user.role, + userGroups: req.user.userGroups || [] // ✅ AJOUTÉ ! + }); }); ``` -## Priorité de Sélection GroupId +## Fix Appliqué -**BACKEND (Sécurité):** -1. `req.body.groupId` si fourni par frontend -2. `user.userGroups[0].groupId` si utilisateur assigné à un groupe ✅ **FIX PRINCIPAL** -3. `1` en fallback d'urgence +### 1. Route `/api/user` corrigée +- ✅ Ajout de `userGroups` dans la réponse JSON +- ✅ Logs debug pour tracer les données utilisateur -**FRONTEND (Logique UI):** -1. Admin avec magasin sélectionné → `selectedStoreId` -2. **Utilisateur avec groupe assigné → `user.userGroups[0].groupId`** ✅ **FIX PRINCIPAL** -3. Admin sans sélection → Premier magasin disponible -4. Fallback d'urgence → `1` +### 2. Logique Frontend maintenant fonctionnelle +```javascript +// Avec userGroups maintenant disponible : +if (user?.userGroups?.[0]?.groupId) { + // ✅ Utilisera le groupe assigné (groupId: 2) + groupId = user.userGroups[0].groupId; +} +``` -## Résultat Attendu +## Résultat Attendu Production -Employé assigné au magasin #2 : -- Frontend calcule `groupId = 2` depuis `user.userGroups[0].groupId` -- Backend valide et crée DLC avec `groupId = 2` -- DLC apparaît dans magasin #2 ✅ +Employé assigné magasin #2 (Houdemont) : +1. **Login** → `/api/user` retourne `userGroups: [{ groupId: 2, group: { name: 'Houdemont' } }]` +2. **Frontend** → Détecte `user.userGroups[0].groupId = 2` +3. **Création DLC** → `groupId: 2` (groupe assigné prioritaire) +4. **Création commande** → `groupId: 2` (groupe assigné prioritaire) +5. **Résultat** → DLC et commandes apparaissent dans magasin #2 ✅ -## Tests de Validation +## Logs Debug Production -✅ Backend force groupId si manquant -✅ Frontend utilise groupe utilisateur -✅ Logs debug pour traçabilité production -✅ Double sécurité frontend + backend +Les nouveaux logs vont confirmer : +``` +🔍 PRODUCTION /api/user - req.user: { + id: '_1753266816257', + role: 'employee', + hasUserGroups: true, + userGroupsLength: 1, + userGroups: [{ groupId: 2, groupName: 'Houdemont' }] +} +``` -**DÉPLOIEMENT PRODUCTION REQUIS** \ No newline at end of file +**DÉPLOIEMENT IMMÉDIAT REQUIS - FIX DEFINITIF** \ No newline at end of file diff --git a/attached_assets/{78D671ED-C43E-41B0-838C-F9066C944DE4}_1755012433773.png b/attached_assets/{78D671ED-C43E-41B0-838C-F9066C944DE4}_1755012433773.png new file mode 100644 index 0000000..ee394d5 Binary files /dev/null and b/attached_assets/{78D671ED-C43E-41B0-838C-F9066C944DE4}_1755012433773.png differ diff --git a/server/localAuth.production.ts b/server/localAuth.production.ts index 01acd25..d00ecef 100644 --- a/server/localAuth.production.ts +++ b/server/localAuth.production.ts @@ -232,6 +232,17 @@ export function setupLocalAuth(app: Express) { // Get current user app.get("/api/user", (req: any, res) => { if (req.isAuthenticated && req.isAuthenticated()) { + console.log("🔍 PRODUCTION /api/user - req.user:", { + id: req.user.id, + role: req.user.role, + hasUserGroups: !!req.user.userGroups, + userGroupsLength: req.user.userGroups?.length, + userGroups: req.user.userGroups?.map((ug: any) => ({ + groupId: ug.groupId || ug.group?.id, + groupName: ug.group?.name + })) + }); + res.json({ id: req.user.id, username: req.user.username, @@ -239,7 +250,8 @@ export function setupLocalAuth(app: Express) { firstName: req.user.firstName, lastName: req.user.lastName, role: req.user.role, - passwordChanged: req.user.passwordChanged + passwordChanged: req.user.passwordChanged, + userGroups: req.user.userGroups || [] // ✅ AJOUT DES USER GROUPS ! }); } else { res.status(401).json({ message: "Not authenticated" });