Fix issue where user groups were not correctly assigned for product creation

Correct the user API endpoint to include user groups in the response, resolving an issue where products were created with incorrect or default group assignments due to missing group data.

Replit-Commit-Author: Agent
Replit-Commit-Session-Id: b163d4c0-de5e-4f4e-a9c0-aed4c7049718
Replit-Commit-Checkpoint-Type: full_checkpoint
Replit-Commit-Screenshot-Url: https://storage.googleapis.com/screenshot-production-us-central1/1957c339-2757-4d1f-8e92-e9f71a1ce58e/b163d4c0-de5e-4f4e-a9c0-aed4c7049718/KQQafdY
This commit is contained in:
michaelschal committed 2025-08-12 15:28:48 +00:00
1 parent 4ede8303ab
commit a2110a84b4
3 files changed
+77 -79

No files matched your search

+64 -78
View File
@@ -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 ## 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 ```javascript
// Erreur de validation backend: // AVANT (Production cassée)
{"message":"Validation error","errors":[{"code":"invalid_type","expected":"number","received":"undefined","path":["groupId"],"message":"Required"}]} 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 // APRÈS (Production fixée)
**CONSÉQUENCE** : DLC pas créée OU créée avec mauvais groupId par défaut app.get("/api/user", (req: any, res) => {
res.json({
## Solutions Appliquées id: req.user.id,
role: req.user.role,
### 1. Fix Backend - Force GroupId Assignment userGroups: req.user.userGroups || [] // ✅ AJOUTÉ !
**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'
}); });
``` ```
## Priorité de Sélection GroupId ## Fix Appliqué
**BACKEND (Sécurité):** ### 1. Route `/api/user` corrigée
1. `req.body.groupId` si fourni par frontend - ✅ Ajout de `userGroups` dans la réponse JSON
2. `user.userGroups[0].groupId` si utilisateur assigné à un groupe ✅ **FIX PRINCIPAL** - ✅ Logs debug pour tracer les données utilisateur
3. `1` en fallback d'urgence
**FRONTEND (Logique UI):** ### 2. Logique Frontend maintenant fonctionnelle
1. Admin avec magasin sélectionné → `selectedStoreId` ```javascript
2. **Utilisateur avec groupe assigné → `user.userGroups[0].groupId`** ✅ **FIX PRINCIPAL** // Avec userGroups maintenant disponible :
3. Admin sans sélection → Premier magasin disponible if (user?.userGroups?.[0]?.groupId) {
4. Fallback d'urgence → `1` // ✅ Utilisera le groupe assigné (groupId: 2)
groupId = user.userGroups[0].groupId;
}
```
## Résultat Attendu ## Résultat Attendu Production
Employé assigné au magasin #2 : Employé assigné magasin #2 (Houdemont) :
- Frontend calcule `groupId = 2` depuis `user.userGroups[0].groupId` 1. **Login** → `/api/user` retourne `userGroups: [{ groupId: 2, group: { name: 'Houdemont' } }]`
- Backend valide et crée DLC avec `groupId = 2` 2. **Frontend** → Détecte `user.userGroups[0].groupId = 2`
- DLC apparaît dans magasin #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 Les nouveaux logs vont confirmer :
✅ Frontend utilise groupe utilisateur ```
✅ Logs debug pour traçabilité production 🔍 PRODUCTION /api/user - req.user: {
✅ Double sécurité frontend + backend id: '_1753266816257',
role: 'employee',
hasUserGroups: true,
userGroupsLength: 1,
userGroups: [{ groupId: 2, groupName: 'Houdemont' }]
}
```
**DÉPLOIEMENT PRODUCTION REQUIS** **DÉPLOIEMENT IMMÉDIAT REQUIS - FIX DEFINITIF**
Binary file not shown.

After

Width:  |  Height:  |  Size: 148 KiB

+13 -1
View File
@@ -232,6 +232,17 @@ export function setupLocalAuth(app: Express) {
// Get current user // Get current user
app.get("/api/user", (req: any, res) => { app.get("/api/user", (req: any, res) => {
if (req.isAuthenticated && req.isAuthenticated()) { 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({ res.json({
id: req.user.id, id: req.user.id,
username: req.user.username, username: req.user.username,
@@ -239,7 +250,8 @@ export function setupLocalAuth(app: Express) {
firstName: req.user.firstName, firstName: req.user.firstName,
lastName: req.user.lastName, lastName: req.user.lastName,
role: req.user.role, role: req.user.role,
passwordChanged: req.user.passwordChanged passwordChanged: req.user.passwordChanged,
userGroups: req.user.userGroups || [] // ✅ AJOUT DES USER GROUPS !
}); });
} else { } else {
res.status(401).json({ message: "Not authenticated" }); res.status(401).json({ message: "Not authenticated" });