Checkpoint: Implémentation de la synchronisation automatique entre table users (role=formateur) et table formateurs : auto-création dans createUser/updateUser + script de migration pour les formateurs existants
This commit is contained in:
40
server/db.ts
40
server/db.ts
@@ -563,6 +563,16 @@ export async function createUser(data: InsertUser) {
|
||||
data.password = await bcrypt.hash(data.password, 10);
|
||||
}
|
||||
|
||||
// Si le rôle est formateur et qu'il n'y a pas de formateurId, créer une entrée dans la table formateurs
|
||||
if (data.role === 'formateur' && !data.formateurId && data.name && data.email) {
|
||||
const formateurResult = await db.insert(formateurs).values({
|
||||
nom: data.name,
|
||||
email: data.email,
|
||||
});
|
||||
// Récupérer l'ID du formateur créé
|
||||
data.formateurId = Number(formateurResult[0].insertId);
|
||||
}
|
||||
|
||||
const result = await db.insert(users).values(data);
|
||||
return result;
|
||||
}
|
||||
@@ -592,6 +602,36 @@ export async function updateUser(id: number, data: Partial<InsertUser>) {
|
||||
data.password = await bcrypt.hash(data.password, 10);
|
||||
}
|
||||
|
||||
// Récupérer l'utilisateur actuel
|
||||
const currentUser = await getUserById(id);
|
||||
if (!currentUser) throw new Error("User not found");
|
||||
|
||||
// Si le rôle change vers formateur et qu'il n'y a pas de formateurId
|
||||
if (data.role === 'formateur' && !currentUser.formateurId && !data.formateurId) {
|
||||
const name = data.name || currentUser.name;
|
||||
const email = data.email || currentUser.email;
|
||||
if (name && email) {
|
||||
const formateurResult = await db.insert(formateurs).values({
|
||||
nom: name,
|
||||
email: email,
|
||||
});
|
||||
data.formateurId = Number(formateurResult[0].insertId);
|
||||
}
|
||||
}
|
||||
|
||||
// Si l'utilisateur est formateur et a un formateurId, synchroniser les modifications
|
||||
if (currentUser.formateurId && (data.name || data.email)) {
|
||||
const formateurUpdate: any = {};
|
||||
if (data.name) formateurUpdate.nom = data.name;
|
||||
if (data.email) formateurUpdate.email = data.email;
|
||||
|
||||
if (Object.keys(formateurUpdate).length > 0) {
|
||||
await db.update(formateurs)
|
||||
.set(formateurUpdate)
|
||||
.where(eq(formateurs.id, currentUser.formateurId));
|
||||
}
|
||||
}
|
||||
|
||||
await db.update(users).set(data).where(eq(users.id, id));
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user