fix(backup): resolve real admin user ID instead of hardcoded 'system' for automatic backups

Fixes FK violation: database_backups.created_by -> users.id
The 'system' user does not exist in the users table, causing
INSERT failures every hour for scheduled backups.
This commit is contained in:
Michael committed 2026-02-10 09:41:12 +01:00
1 parent cb1a1a933c
commit 40cf456a64
1 file changed
+45 -4
+45 -4
View File
@@ -5,7 +5,7 @@ import path from 'path';
import { nanoid } from 'nanoid'; import { nanoid } from 'nanoid';
import { eq, desc } from "drizzle-orm"; import { eq, desc } from "drizzle-orm";
import { db } from "./db"; import { db } from "./db";
import { databaseBackups, utilities } from "@shared/schema"; import { databaseBackups, utilities, users } from "@shared/schema";
import type { DatabaseBackup, InsertDatabaseBackup } from "@shared/schema"; import type { DatabaseBackup, InsertDatabaseBackup } from "@shared/schema";
const execAsync = promisify(exec); const execAsync = promisify(exec);
@@ -70,6 +70,31 @@ export class BackupService {
}; };
} }
/**
* Resolve a valid user ID for system-initiated backups.
* Returns the first admin user ID, or the first user if no admin exists.
* This avoids FK violations on database_backups.created_by -> users.id.
*/
private async resolveSystemUserId(): Promise<string | null> {
try {
// Try to find an admin user first
const [adminUser] = await db.select({ id: users.id })
.from(users)
.where(eq(users.role, 'admin'))
.limit(1);
if (adminUser) return adminUser.id;
// Fallback: any existing user
const [anyUser] = await db.select({ id: users.id })
.from(users)
.limit(1);
return anyUser?.id ?? null;
} catch (error) {
console.error('❌ Failed to resolve system user ID for backup:', error);
return null;
}
}
async createBackup(type: 'manual' | 'automatic' = 'manual', createdBy: string = 'system'): Promise<DatabaseBackup> { async createBackup(type: 'manual' | 'automatic' = 'manual', createdBy: string = 'system'): Promise<DatabaseBackup> {
try { try {
const id = nanoid(); const id = nanoid();
@@ -240,10 +265,20 @@ export class BackupService {
const lastBackup = existingBackupToday[0]; const lastBackup = existingBackupToday[0];
const lastBackupDate = lastBackup ? lastBackup.createdAt.toISOString().split('T')[0] : null; const lastBackupDate = lastBackup ? lastBackup.createdAt.toISOString().split('T')[0] : null;
// Si aucune sauvegarde automatique aujourd'hui, en créer une // Only perform backup if no automatic backup exists for today
if (lastBackupDate !== today) { if (lastBackupDate !== today) {
// Resolve a real user ID if called with default 'system'
let resolvedUserId = userId;
if (userId === 'system') {
const systemId = await this.resolveSystemUserId();
if (!systemId) {
console.warn('⚠️ No user found in database — skipping daily backup');
return { backupPerformed: false, message: 'Aucun utilisateur trouvé pour la sauvegarde' };
}
resolvedUserId = systemId;
}
console.log('🔄 Première connexion du jour - Création de la sauvegarde automatique...'); console.log('🔄 Première connexion du jour - Création de la sauvegarde automatique...');
await this.createBackup('automatic', userId); await this.createBackup('automatic', resolvedUserId);
console.log('✅ Sauvegarde quotidienne effectuée avec succès'); console.log('✅ Sauvegarde quotidienne effectuée avec succès');
return { return {
backupPerformed: true, backupPerformed: true,
@@ -298,8 +333,14 @@ export class BackupService {
// Only proceed if no automatic backup exists for today // Only proceed if no automatic backup exists for today
if (lastBackupDate !== today) { if (lastBackupDate !== today) {
// Resolve a real user ID to satisfy FK constraint
const systemUserId = await this.resolveSystemUserId();
if (!systemUserId) {
console.warn('⚠️ No user found in database — skipping automatic backup');
return;
}
console.log('🔄 Starting automatic backup...'); console.log('🔄 Starting automatic backup...');
await this.createBackup('automatic', 'system'); await this.createBackup('automatic', systemUserId);
this.lastAutomaticBackupDate = today; this.lastAutomaticBackupDate = today;
console.log('✅ Automatic backup completed'); console.log('✅ Automatic backup completed');
} }