mirror of
https://github.com/donpat1to/Schichtenplaner.git
synced 2025-12-01 06:55:45 +01:00
added setup files
This commit is contained in:
@@ -6,17 +6,31 @@ import { db } from '../services/databaseService.js';
|
||||
|
||||
export const checkSetupStatus = async (req: Request, res: Response): Promise<void> => {
|
||||
try {
|
||||
const adminExists = await db.get<{ count: number }>(
|
||||
'SELECT COUNT(*) as count FROM users WHERE role = ?',
|
||||
['admin']
|
||||
);
|
||||
// First, ensure database is properly initialized
|
||||
try {
|
||||
const adminExists = await db.get<{ count: number }>(
|
||||
'SELECT COUNT(*) as count FROM users WHERE role = ?',
|
||||
['admin']
|
||||
);
|
||||
|
||||
res.json({
|
||||
needsSetup: !adminExists || adminExists.count === 0
|
||||
});
|
||||
res.json({
|
||||
needsSetup: !adminExists || adminExists.count === 0,
|
||||
message: adminExists && adminExists.count > 0 ? 'Admin user exists' : 'No admin user found'
|
||||
});
|
||||
} catch (dbError) {
|
||||
console.error('Database error in checkSetupStatus:', dbError);
|
||||
// If there's a database error, assume setup is needed
|
||||
res.json({
|
||||
needsSetup: true,
|
||||
message: 'Database not ready, setup required'
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error checking setup status:', error);
|
||||
res.status(500).json({ error: 'Internal server error' });
|
||||
res.status(500).json({
|
||||
error: 'Internal server error',
|
||||
needsSetup: true
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
@@ -78,7 +92,8 @@ export const setupAdmin = async (req: Request, res: Response): Promise<void> =>
|
||||
|
||||
res.status(201).json({
|
||||
message: 'Admin user created successfully',
|
||||
userId: adminId
|
||||
userId: adminId,
|
||||
email: email
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error in setup:', error);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
// backend/src/routes/setup.ts
|
||||
import express from 'express';
|
||||
import bcrypt from 'bcryptjs';
|
||||
import { checkSetupStatus, setupAdmin } from '../controllers/setupController.js';
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
// backend/src/scripts/initializeDatabase.ts
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
@@ -14,6 +15,20 @@ export async function initializeDatabase(): Promise<void> {
|
||||
try {
|
||||
console.log('Starting database initialization...');
|
||||
|
||||
// Check if users table exists and has data
|
||||
try {
|
||||
const existingAdmin = await db.get<{ count: number }>(
|
||||
"SELECT COUNT(*) as count FROM users WHERE role = 'admin'"
|
||||
);
|
||||
|
||||
if (existingAdmin && existingAdmin.count > 0) {
|
||||
console.log('✅ Database already initialized with admin user');
|
||||
return;
|
||||
}
|
||||
} catch (error) {
|
||||
console.log('ℹ️ Database tables might not exist yet, creating schema...');
|
||||
}
|
||||
|
||||
// Get list of existing tables
|
||||
interface TableInfo {
|
||||
name: string;
|
||||
@@ -26,7 +41,7 @@ export async function initializeDatabase(): Promise<void> {
|
||||
|
||||
console.log('Existing tables found:', existingTables.map(t => t.name).join(', ') || 'none');
|
||||
|
||||
// Drop existing tables in reverse order of dependencies
|
||||
// Drop existing tables in reverse order of dependencies if they exist
|
||||
const tablesToDrop = [
|
||||
'employee_availabilities',
|
||||
'assigned_shifts',
|
||||
@@ -77,54 +92,13 @@ export async function initializeDatabase(): Promise<void> {
|
||||
}
|
||||
|
||||
await db.run('COMMIT');
|
||||
console.log('✅ Datenbankschema erfolgreich initialisiert');
|
||||
console.log('✅ Database schema successfully initialized');
|
||||
|
||||
// Give a small delay to ensure all transactions are properly closed
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
|
||||
// Create default template
|
||||
await setupDefaultTemplate();
|
||||
} catch (error) {
|
||||
console.error('Fehler bei der Datenbankinitialisierung:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async function createAdminUser(): Promise<void> {
|
||||
try {
|
||||
await db.run('BEGIN TRANSACTION');
|
||||
|
||||
try {
|
||||
// Erstelle Admin-Benutzer, wenn noch keiner existiert
|
||||
const admin = await db.get('SELECT id FROM users WHERE role = ?', ['admin']);
|
||||
|
||||
if (!admin) {
|
||||
await db.run(
|
||||
`INSERT INTO users (id, email, password, name, role, phone, department, is_active)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
[
|
||||
'admin-' + Math.random().toString(36).substring(2),
|
||||
'admin@schichtplan.de',
|
||||
'admin123',
|
||||
'Administrator',
|
||||
'admin',
|
||||
'+49 123 456789',
|
||||
'IT',
|
||||
true
|
||||
]
|
||||
);
|
||||
console.log('✅ Admin-Benutzer erstellt');
|
||||
} else {
|
||||
console.log('ℹ️ Admin-Benutzer existiert bereits');
|
||||
}
|
||||
|
||||
await db.run('COMMIT');
|
||||
} catch (error) {
|
||||
await db.run('ROLLBACK');
|
||||
throw error;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Fehler beim Erstellen des Admin-Benutzers:', error);
|
||||
console.error('Error during database initialization:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
// backend/src/server.ts - Login für alle Benutzer
|
||||
// backend/src/server.ts
|
||||
import express from 'express';
|
||||
import cors from 'cors';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
import { setupDefaultTemplate } from './scripts/setupDefaultTemplate.js';
|
||||
import { initializeDatabase } from './scripts/initializeDatabase.js';
|
||||
|
||||
@@ -38,6 +37,29 @@ app.get('/api/health', (req: any, res: any) => {
|
||||
});
|
||||
});
|
||||
|
||||
// Setup status route (additional endpoint for clarity)
|
||||
app.get('/api/initial-setup', async (req: any, res: any) => {
|
||||
try {
|
||||
const { db } = await import('./services/databaseService.js');
|
||||
|
||||
// Define proper interface for the result
|
||||
interface AdminCountResult {
|
||||
count: number;
|
||||
}
|
||||
|
||||
const adminExists = await db.get<AdminCountResult>(
|
||||
'SELECT COUNT(*) as count FROM users WHERE role = ?',
|
||||
['admin']
|
||||
);
|
||||
|
||||
res.json({
|
||||
needsInitialSetup: !adminExists || adminExists.count === 0
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error checking initial setup:', error);
|
||||
res.status(500).json({ error: 'Internal server error' });
|
||||
}
|
||||
});
|
||||
|
||||
// Start server
|
||||
app.listen(PORT, async () => {
|
||||
@@ -47,13 +69,15 @@ app.listen(PORT, async () => {
|
||||
|
||||
try {
|
||||
await initializeDatabase();
|
||||
console.log('✅ Database initialized successfully');
|
||||
|
||||
await setupDefaultTemplate();
|
||||
console.log('✅ Standard-Vorlage überprüft/erstellt');
|
||||
console.log('✅ Default template checked/created');
|
||||
} catch (error) {
|
||||
console.error('❌ Fehler bei der Initialisierung:', error);
|
||||
console.error('❌ Error during initialization:', error);
|
||||
}
|
||||
|
||||
console.log('');
|
||||
console.log('🔧 Setup ready at: http://localhost:${PORT}/api/setup/status');
|
||||
console.log(`🔧 Setup ready at: http://localhost:${PORT}/api/setup/status`);
|
||||
console.log('📝 Create your admin account on first launch');
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user