settings works for every user

This commit is contained in:
2025-10-13 14:34:45 +02:00
parent dec92daf7c
commit b6fd57dfc7
13 changed files with 505 additions and 456 deletions

View File

@@ -372,6 +372,15 @@ export const changePassword = async (req: AuthRequest, res: Response): Promise<v
const { id } = req.params;
const { currentPassword, newPassword } = req.body;
// Get the current user from the auth middleware
const currentUser = (req as AuthRequest).user;
// Check if user is changing their own password or is an admin
if (currentUser?.userId !== id && currentUser?.role !== 'admin') {
res.status(403).json({ error: 'You can only change your own password' });
return;
}
// Check if employee exists and get password
const employee = await db.get<{ password: string }>('SELECT password FROM employees WHERE id = ?', [id]);
if (!employee) {
@@ -379,10 +388,18 @@ export const changePassword = async (req: AuthRequest, res: Response): Promise<v
return;
}
// Verify current password
const isValidPassword = await bcrypt.compare(currentPassword, employee.password);
if (!isValidPassword) {
res.status(400).json({ error: 'Current password is incorrect' });
// For non-admin users, verify current password
if (currentUser?.role !== 'admin') {
const isValidPassword = await bcrypt.compare(currentPassword, employee.password);
if (!isValidPassword) {
res.status(400).json({ error: 'Current password is incorrect' });
return;
}
}
// Validate new password
if (!newPassword || newPassword.length < 6) {
res.status(400).json({ error: 'New password must be at least 6 characters long' });
return;
}

View File

@@ -681,7 +681,7 @@ async function generateScheduledShifts(planId: string, startDate: string, endDat
}
}
export const getTemplates = async (req: Request, res: Response): Promise<void> => {
/*export const getTemplates = async (req: Request, res: Response): Promise<void> => {
try {
console.log('🔍 Lade Vorlagen...');
@@ -707,7 +707,7 @@ export const getTemplates = async (req: Request, res: Response): Promise<void> =
console.error('Error fetching templates:', error);
res.status(500).json({ error: 'Internal server error' });
}
};
};*/
// Neue Funktion: Create from Template
/*export const createFromTemplate = async (req: Request, res: Response): Promise<void> => {

View File

@@ -23,10 +23,10 @@ router.get('/:id', requireRole(['admin', 'instandhalter']), getEmployee);
router.post('/', requireRole(['admin']), createEmployee);
router.put('/:id', requireRole(['admin']), updateEmployee);
router.delete('/:id', requireRole(['admin']), deleteEmployee);
router.put('/:id/password', requireRole(['admin']), changePassword);
router.put('/:id/password', authMiddleware, changePassword);
// Availability Routes
router.get('/:employeeId/availabilities', requireRole(['admin', 'instandhalter']), getAvailabilities);
router.put('/:employeeId/availabilities', requireRole(['admin', 'instandhalter']), updateAvailabilities);
router.get('/:employeeId/availabilities', authMiddleware, getAvailabilities);
router.put('/:employeeId/availabilities', authMiddleware, updateAvailabilities);
export default router;

View File

@@ -7,7 +7,7 @@ import {
createShiftPlan,
updateShiftPlan,
deleteShiftPlan,
getTemplates,
//getTemplates,
//createFromTemplate,
createFromPreset
} from '../controllers/shiftPlanController.js';
@@ -22,7 +22,7 @@ router.use(authMiddleware);
router.get('/', getShiftPlans);
// GET templates only
router.get('/templates', getTemplates);
//router.get('/templates', getTemplates);
// GET specific shift plan or template
router.get('/:id', getShiftPlan);

View File

@@ -3,7 +3,6 @@ import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import { db } from '../services/databaseService.js';
import { setupDefaultTemplate } from './setupDefaultTemplate.js';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

View File

@@ -1,127 +0,0 @@
// backend/src/scripts/setupDefaultTemplate.ts
import { v4 as uuidv4 } from 'uuid';
import { db } from '../services/databaseService.js';
import { DEFAULT_ZEBRA_TIME_SLOTS } from '../models/defaults/shiftPlanDefaults.js';
interface AdminUser {
id: string;
}
/**
* Sets up the default shift template if it doesn't exist
* @returns {Promise<void>}
*/
export async function setupDefaultTemplate(): Promise<void> {
try {
// Prüfen ob bereits eine Standard-Vorlage existiert - KORREKTUR: shift_plans verwenden
const existingDefault = await db.get(
'SELECT * FROM shift_plans WHERE is_template = 1 AND name = ?',
['Standardwoche']
);
if (existingDefault) {
console.log('Standard-Vorlage existiert bereits');
return;
}
// Admin-Benutzer für die Standard-Vorlage finden - KORREKTUR: employees verwenden
const adminUser = await db.get<AdminUser>(
'SELECT id FROM employees WHERE role = ?',
['admin']
);
if (!adminUser) {
console.log('Kein Admin-Benutzer gefunden. Standard-Vorlage kann nicht erstellt werden.');
return;
}
const templateId = uuidv4();
console.log('🔄 Erstelle Standard-Vorlage mit ID:', templateId);
// Transaktion starten
await db.run('BEGIN TRANSACTION');
try {
// Standard-Vorlage erstellen - KORREKTUR: shift_plans verwenden
await db.run(
`INSERT INTO shift_plans (id, name, description, is_template, status, created_by)
VALUES (?, ?, ?, ?, ?, ?)`,
[
templateId,
'Standardwoche',
'Mo-Do: Vormittags- und Nachmittagsschicht, Fr: nur Vormittagsschicht',
1, // is_template = true
'template', // status = 'template'
adminUser.id
]
);
console.log('Standard-Vorlage erstellt:', templateId);
// Zeit-Slots erstellen - KORREKTUR: time_slots verwenden
const timeSlots = DEFAULT_ZEBRA_TIME_SLOTS.map(slot => ({
...slot,
id: uuidv4()
}));
for (const slot of timeSlots) {
await db.run(
`INSERT INTO time_slots (id, plan_id, name, start_time, end_time, description)
VALUES (?, ?, ?, ?, ?, ?)`,
[slot.id, templateId, slot.name, slot.startTime, slot.endTime, slot.description]
);
}
console.log('✅ Zeit-Slots erstellt');
// Schichten für Mo-Do - KORREKTUR: shifts verwenden
for (let day = 1; day <= 4; day++) {
// Vormittagsschicht
await db.run(
`INSERT INTO shifts (id, plan_id, day_of_week, time_slot_id, required_employees, color)
VALUES (?, ?, ?, ?, ?, ?)`,
[uuidv4(), templateId, day, timeSlots[0].id, 2, '#3498db']
);
// Nachmittagsschicht
await db.run(
`INSERT INTO shifts (id, plan_id, day_of_week, time_slot_id, required_employees, color)
VALUES (?, ?, ?, ?, ?, ?)`,
[uuidv4(), templateId, day, timeSlots[1].id, 2, '#e74c3c']
);
}
// Freitag nur Vormittagsschicht
await db.run(
`INSERT INTO shifts (id, plan_id, day_of_week, time_slot_id, required_employees, color)
VALUES (?, ?, ?, ?, ?, ?)`,
[uuidv4(), templateId, 5, timeSlots[0].id, 2, '#3498db']
);
console.log('✅ Schichten erstellt');
// In der problematischen Stelle: KORREKTUR: shift_plans verwenden
const createdTemplate = await db.get(
'SELECT * FROM shift_plans WHERE id = ?',
[templateId]
) as { name: string } | undefined;
console.log('📋 Erstellte Vorlage:', createdTemplate?.name);
const shiftCount = await db.get(
'SELECT COUNT(*) as count FROM shifts WHERE plan_id = ?',
[templateId]
) as { count: number } | undefined;
console.log(`📊 Anzahl Schichten: ${shiftCount?.count}`);
await db.run('COMMIT');
console.log('🎉 Standard-Vorlage erfolgreich initialisiert');
} catch (error) {
await db.run('ROLLBACK');
console.error('❌ Fehler beim Erstellen der Vorlage:', error);
throw error;
}
} catch (error) {
console.error('❌ Fehler in setupDefaultTemplate:', error);
}
}

View File

@@ -1,7 +1,6 @@
// backend/src/server.ts
import express from 'express';
import cors from 'cors';
import { setupDefaultTemplate } from './scripts/setupDefaultTemplate.js';
import { initializeDatabase } from './scripts/initializeDatabase.js';
// Route imports
@@ -62,10 +61,6 @@ const initializeApp = async () => {
const { applyMigration } = await import('./scripts/applyMigration.js');
await applyMigration();
//console.log('✅ Database migrations applied');
// Setup default template
await setupDefaultTemplate();
//console.log('✅ Default template checked/created');
// Start server only after successful initialization
app.listen(PORT, () => {