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
### ✅ 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**
**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
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" });