Compare commits

...

3 Commits

Author SHA1 Message Date
0b46919e46 fixed role handling in getshiftplanbyid 2025-11-03 23:16:53 +01:00
65cb3e72ba added backend for shiftplan export 2025-11-03 22:50:02 +01:00
dab5164704 added exporting files 2025-11-03 22:07:32 +01:00
6 changed files with 480 additions and 26 deletions

View File

@@ -592,6 +592,26 @@ async function getShiftPlanById(planId: string): Promise<any> {
`, [planId]);
}
// Load employees without role column + join with employee_roles
const employees = await db.all<any>(`
SELECT
e.id,
e.firstname,
e.lastname,
e.email,
e.employee_type,
e.contract_type,
e.can_work_alone,
e.is_trainee,
e.is_active as isActive,
GROUP_CONCAT(er.role) as roles
FROM employees e
LEFT JOIN employee_roles er ON e.id = er.employee_id
WHERE e.is_active = 1
GROUP BY e.id
ORDER BY e.firstname, e.lastname
`, []);
return {
...plan,
isTemplate: plan.is_template === 1,
@@ -629,6 +649,19 @@ async function getShiftPlanById(planId: string): Promise<any> {
requiredEmployees: shift.required_employees,
assignedEmployees: JSON.parse(shift.assigned_employees || '[]'),
timeSlotName: shift.time_slot_name
})),
// Include employees with proper role handling
employees: employees.map(emp => ({
id: emp.id,
firstname: emp.firstname,
lastname: emp.lastname,
email: emp.email,
employeeType: emp.employee_type,
contractType: emp.contract_type,
canWorkAlone: emp.can_work_alone === 1,
isTrainee: emp.is_trainee === 1,
isActive: emp.isActive === 1,
roles: emp.roles ? emp.roles.split(',') : [] // Convert comma-separated roles to array
}))
};
}
@@ -932,4 +965,247 @@ export const clearAssignments = async (req: Request, res: Response): Promise<voi
console.error('❌ Error clearing assignments:', error);
res.status(500).json({ error: 'Internal server error' });
}
};
};
export const exportShiftPlanToExcel = async (req: Request, res: Response): Promise<void> => {
try {
const { id } = req.params;
console.log('📊 Starting Excel export for plan:', id);
// Check if plan exists
const plan = await getShiftPlanById(id);
if (!plan) {
res.status(404).json({ error: 'Shift plan not found' });
return;
}
if (plan.status !== 'published') {
res.status(400).json({ error: 'Can only export published shift plans' });
return;
}
// For now, return a simple CSV as placeholder
// In a real implementation, you would use a library like exceljs or xlsx
const csvData = generateCSVFromPlan(plan);
res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
res.setHeader('Content-Disposition', `attachment; filename="Schichtplan_${plan.name}_${new Date().toISOString().split('T')[0]}.xlsx"`);
// For now, return CSV as placeholder - replace with actual Excel generation
res.setHeader('Content-Type', 'text/csv');
res.setHeader('Content-Disposition', `attachment; filename="Schichtplan_${plan.name}_${new Date().toISOString().split('T')[0]}.csv"`);
res.send(csvData);
console.log('✅ Excel export completed for plan:', id);
} catch (error) {
console.error('❌ Error exporting to Excel:', error);
res.status(500).json({ error: 'Internal server error during Excel export' });
}
};
export const exportShiftPlanToPDF = async (req: Request, res: Response): Promise<void> => {
try {
const { id } = req.params;
console.log('📄 Starting PDF export for plan:', id);
// Check if plan exists
const plan = await getShiftPlanById(id);
if (!plan) {
res.status(404).json({ error: 'Shift plan not found' });
return;
}
if (plan.status !== 'published') {
res.status(400).json({ error: 'Can only export published shift plans' });
return;
}
// For now, return a simple HTML as placeholder
// In a real implementation, you would use a library like pdfkit, puppeteer, or html-pdf
const pdfData = generateHTMLFromPlan(plan);
res.setHeader('Content-Type', 'application/pdf');
res.setHeader('Content-Disposition', `attachment; filename="Schichtplan_${plan.name}_${new Date().toISOString().split('T')[0]}.pdf"`);
// For now, return HTML as placeholder - replace with actual PDF generation
res.setHeader('Content-Type', 'text/html');
res.setHeader('Content-Disposition', `attachment; filename="Schichtplan_${plan.name}_${new Date().toISOString().split('T')[0]}.html"`);
res.send(pdfData);
console.log('✅ PDF export completed for plan:', id);
} catch (error) {
console.error('❌ Error exporting to PDF:', error);
res.status(500).json({ error: 'Internal server error during PDF export' });
}
};
// Helper function to generate CSV data
function generateCSVFromPlan(plan: any): string {
const headers = ['Datum', 'Tag', 'Schicht', 'Zeit', 'Zugewiesene Mitarbeiter', 'Benötigte Mitarbeiter'];
const rows: string[] = [headers.join(';')];
// Group scheduled shifts by date for better organization
const shiftsByDate = new Map();
plan.scheduledShifts?.forEach((scheduledShift: any) => {
const date = scheduledShift.date;
if (!shiftsByDate.has(date)) {
shiftsByDate.set(date, []);
}
shiftsByDate.get(date).push(scheduledShift);
});
// Sort dates chronologically
const sortedDates = Array.from(shiftsByDate.keys()).sort();
sortedDates.forEach(date => {
const dateShifts = shiftsByDate.get(date);
const dateObj = new Date(date);
const dayName = getGermanDayName(dateObj.getDay());
dateShifts.forEach((scheduledShift: any) => {
const timeSlot = plan.timeSlots?.find((ts: any) => ts.id === scheduledShift.timeSlotId);
const employeeNames = scheduledShift.assignedEmployees.map((empId: string) => {
const employee = plan.employees?.find((emp: any) => emp.id === empId);
return employee ? `${employee.firstname} ${employee.lastname}` : 'Unbekannt';
}).join(', ');
const row = [
date,
dayName,
timeSlot?.name || 'Unbekannt',
timeSlot ? `${timeSlot.startTime} - ${timeSlot.endTime}` : '',
employeeNames || 'Keine Zuweisungen',
scheduledShift.requiredEmployees || 2
].map(field => `"${field}"`).join(';');
rows.push(row);
});
});
// Add plan summary
rows.push('');
rows.push('Plan Zusammenfassung');
rows.push(`"Plan Name";"${plan.name}"`);
rows.push(`"Zeitraum";"${plan.startDate} bis ${plan.endDate}"`);
rows.push(`"Status";"${plan.status}"`);
rows.push(`"Erstellt von";"${plan.created_by_name || 'Unbekannt'}"`);
rows.push(`"Erstellt am";"${plan.createdAt}"`);
rows.push(`"Anzahl Schichten";"${plan.scheduledShifts?.length || 0}"`);
return rows.join('\n');
}
// Helper function to generate HTML data
function generateHTMLFromPlan(plan: any): string {
const shiftsByDate = new Map();
plan.scheduledShifts?.forEach((scheduledShift: any) => {
const date = scheduledShift.date;
if (!shiftsByDate.has(date)) {
shiftsByDate.set(date, []);
}
shiftsByDate.get(date).push(scheduledShift);
});
const sortedDates = Array.from(shiftsByDate.keys()).sort();
let html = `
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Schichtplan: ${plan.name}</title>
<style>
body { font-family: Arial, sans-serif; margin: 20px; }
h1 { color: #2c3e50; }
h2 { color: #34495e; margin-top: 30px; }
table { width: 100%; border-collapse: collapse; margin-bottom: 20px; }
th, td { border: 1px solid #ddd; padding: 12px; text-align: left; }
th { background-color: #f2f2f2; font-weight: bold; }
tr:nth-child(even) { background-color: #f9f9f9; }
.summary { background-color: #e8f4fd; padding: 15px; border-radius: 5px; margin-bottom: 20px; }
.date-section { margin-bottom: 30px; }
</style>
</head>
<body>
<h1>Schichtplan: ${plan.name}</h1>
<div class="summary">
<h2>Plan Informationen</h2>
<p><strong>Zeitraum:</strong> ${plan.startDate} bis ${plan.endDate}</p>
<p><strong>Status:</strong> ${plan.status}</p>
<p><strong>Erstellt von:</strong> ${plan.created_by_name || 'Unbekannt'}</p>
<p><strong>Erstellt am:</strong> ${plan.createdAt}</p>
<p><strong>Anzahl Schichten:</strong> ${plan.scheduledShifts?.length || 0}</p>
</div>
<h2>Schichtzuweisungen</h2>
`;
sortedDates.forEach(date => {
const dateShifts = shiftsByDate.get(date);
const dateObj = new Date(date);
const dayName = getGermanDayName(dateObj.getDay());
html += `
<div class="date-section">
<h3>${date} (${dayName})</h3>
<table>
<thead>
<tr>
<th>Schicht</th>
<th>Zeit</th>
<th>Zugewiesene Mitarbeiter</th>
<th>Benötigte Mitarbeiter</th>
</tr>
</thead>
<tbody>
`;
dateShifts.forEach((scheduledShift: any) => {
const timeSlot = plan.timeSlots?.find((ts: any) => ts.id === scheduledShift.timeSlotId);
const employeeNames = scheduledShift.assignedEmployees.map((empId: string) => {
const employee = plan.employees?.find((emp: any) => emp.id === empId);
return employee ? `${employee.firstname} ${employee.lastname}` : 'Unbekannt';
}).join(', ') || 'Keine Zuweisungen';
html += `
<tr>
<td>${timeSlot?.name || 'Unbekannt'}</td>
<td>${timeSlot ? `${timeSlot.startTime} - ${timeSlot.endTime}` : ''}</td>
<td>${employeeNames}</td>
<td>${scheduledShift.requiredEmployees || 2}</td>
</tr>
`;
});
html += `
</tbody>
</table>
</div>
`;
});
html += `
<div style="margin-top: 40px; font-size: 12px; color: #666; text-align: center;">
Erstellt am: ${new Date().toLocaleString('de-DE')}
</div>
</body>
</html>
`;
return html;
}
// Helper function to get German day names
function getGermanDayName(dayIndex: number): string {
const days = ['Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag'];
return days[dayIndex];
}

View File

@@ -7,7 +7,9 @@ import {
updateShiftPlan,
deleteShiftPlan,
createFromPreset,
clearAssignments
clearAssignments,
exportShiftPlanToExcel,
exportShiftPlanToPDF
} from '../controllers/shiftPlanController.js';
import {
validateShiftPlan,
@@ -30,4 +32,7 @@ router.put('/:id', validateId, validateShiftPlanUpdate, handleValidationErrors,
router.delete('/:id', validateId, handleValidationErrors, requireRole(['admin', 'maintenance']), deleteShiftPlan);
router.post('/:id/clear-assignments', validateId, handleValidationErrors, requireRole(['admin', 'maintenance']), clearAssignments);
router.get('/:id/export/excel', validateId, handleValidationErrors, requireRole(['admin', 'maintenance']), exportShiftPlanToExcel);
router.get('/:id/export/pdf', validateId, handleValidationErrors, requireRole(['admin', 'maintenance']), exportShiftPlanToPDF);
export default router;

View File

@@ -27,7 +27,10 @@
"esbuild": "^0.21.0",
"terser": "5.44.0",
"babel-plugin-transform-remove-console": "6.9.4",
"framer-motion": "12.23.24"
"framer-motion": "12.23.24",
"file-saver": "2.0.5",
"@types/file-saver": "2.0.5"
},
"scripts": {
"dev": "vite dev",

View File

@@ -10,6 +10,7 @@ import { ShiftPlan, TimeSlot, ScheduledShift } from '../../models/ShiftPlan';
import { Employee, EmployeeAvailability } from '../../models/Employee';
import { useNotification } from '../../contexts/NotificationContext';
import { formatDate, formatTime } from '../../utils/foramatters';
import { saveAs } from 'file-saver';
// Local interface extensions (same as AvailabilityManager)
interface ExtendedTimeSlot extends TimeSlot {
@@ -54,6 +55,7 @@ const ShiftPlanView: React.FC = () => {
const [scheduledShifts, setScheduledShifts] = useState<ScheduledShift[]>([]);
const [showAssignmentPreview, setShowAssignmentPreview] = useState(false);
const [recreating, setRecreating] = useState(false);
const [exporting, setExporting] = useState(false);
useEffect(() => {
loadShiftPlanData();
@@ -240,6 +242,66 @@ const ShiftPlanView: React.FC = () => {
};
};
const handleExportExcel = async () => {
if (!shiftPlan) return;
try {
setExporting(true);
// Call the export service
const blob = await shiftPlanService.exportShiftPlanToExcel(shiftPlan.id);
// Use file-saver to download the file
saveAs(blob, `Schichtplan_${shiftPlan.name}_${new Date().toISOString().split('T')[0]}.xlsx`);
showNotification({
type: 'success',
title: 'Export erfolgreich',
message: 'Der Schichtplan wurde als Excel-Datei exportiert.'
});
} catch (error) {
console.error('Error exporting to Excel:', error);
showNotification({
type: 'error',
title: 'Export fehlgeschlagen',
message: 'Der Excel-Export konnte nicht durchgeführt werden.'
});
} finally {
setExporting(false);
}
};
const handleExportPDF = async () => {
if (!shiftPlan) return;
try {
setExporting(true);
// Call the PDF export service
const blob = await shiftPlanService.exportShiftPlanToPDF(shiftPlan.id);
// Use file-saver to download the file
saveAs(blob, `Schichtplan_${shiftPlan.name}_${new Date().toISOString().split('T')[0]}.pdf`);
showNotification({
type: 'success',
title: 'Export erfolgreich',
message: 'Der Schichtplan wurde als PDF exportiert.'
});
} catch (error) {
console.error('Error exporting to PDF:', error);
showNotification({
type: 'error',
title: 'Export fehlgeschlagen',
message: 'Der PDF-Export konnte nicht durchgeführt werden.'
});
} finally {
setExporting(false);
}
};
const loadShiftPlanData = async () => {
if (!id) return;
@@ -399,12 +461,12 @@ const ShiftPlanView: React.FC = () => {
console.log('- Scheduled Shifts:', scheduledShifts.length);
// DEBUG: Show shift pattern IDs
if (shiftPlan.shifts) {
/*if (shiftPlan.shifts) {
console.log('📋 SHIFT PATTERN IDs:');
shiftPlan.shifts.forEach((shift, index) => {
console.log(` ${index + 1}. ${shift.id} (Day ${shift.dayOfWeek}, TimeSlot ${shift.timeSlotId})`);
});
}
}*/
const constraints = {
enforceNoTraineeAlone: true,
@@ -650,6 +712,20 @@ const ShiftPlanView: React.FC = () => {
return employeesWithoutAvailabilities.length === 0;
};
const canPublishAssignment = (): boolean => {
if (!assignmentResult) return false;
// Check if assignment was successful
if (assignmentResult.success === false) return false;
// Check if there are any critical violations
const hasCriticalViolations = assignmentResult.violations.some(v =>
v.includes('ERROR:') || v.includes('KRITISCH:')
);
return !hasCriticalViolations;
};
const getAvailabilityStatus = () => {
const totalEmployees = employees.length;
const employeesWithAvailabilities = new Set(
@@ -1005,7 +1081,50 @@ const ShiftPlanView: React.FC = () => {
</div>
</div>
<div style={{ display: 'flex', gap: '10px', alignItems: 'center' }}>
{shiftPlan.status === 'published' && hasRole(['admin', 'maintenance']) && (
{shiftPlan.status === 'published' && hasRole(['admin', 'maintenance']) && (
<>
<button
onClick={handleExportExcel}
disabled={exporting}
style={{
padding: '10px 20px',
backgroundColor: '#27ae60',
color: 'white',
border: 'none',
borderRadius: '4px',
cursor: exporting ? 'not-allowed' : 'pointer',
fontWeight: 'bold',
display: 'flex',
alignItems: 'center',
gap: '8px'
}}
>
{exporting ? '🔄' : '📊'} {exporting ? 'Exportiert...' : 'Excel Export'}
</button>
<button
onClick={handleExportPDF}
disabled={exporting}
style={{
padding: '10px 20px',
backgroundColor: '#e74c3c',
color: 'white',
border: 'none',
borderRadius: '4px',
cursor: exporting ? 'not-allowed' : 'pointer',
fontWeight: 'bold',
display: 'flex',
alignItems: 'center',
gap: '8px'
}}
>
{exporting ? '🔄' : '📄'} {exporting ? 'Exportiert...' : 'PDF Export'}
</button>
</>
)}
{/* Your existing "Zuweisungen neu berechnen" button */}
{shiftPlan.status === 'published' && hasRole(['admin', 'maintenance']) && (
<button
onClick={handleRecreateAssignments}
disabled={recreating}
@@ -1197,15 +1316,13 @@ const ShiftPlanView: React.FC = () => {
</div>
)}
{/* KORRIGIERTE ZUSAMMENFASSUNG */}
{/* ZUSAMMENFASSUNG */}
{assignmentResult && (
<div style={{ marginBottom: '20px' }}>
<h4>Zusammenfassung:</h4>
{/* Entscheidung basierend auf tatsächlichen kritischen Problemen */}
{assignmentResult.violations.filter(v =>
v.includes('ERROR:') || v.includes('❌ KRITISCH:')
).length === 0 ? (
{(assignmentResult.violations.length === 0) || assignmentResult.success == true ? (
<div style={{
padding: '15px',
backgroundColor: '#d4edda',
@@ -1291,29 +1408,21 @@ const ShiftPlanView: React.FC = () => {
{/* KORRIGIERTER BUTTON MIT TYPESCRIPT-FIX */}
<button
onClick={handlePublish}
disabled={publishing || (assignmentResult ? assignmentResult.violations.filter(v =>
v.includes('ERROR:') || v.includes('❌ KRITISCH:')
).length > 0 : true)}
disabled={publishing || !canPublishAssignment()}
style={{
padding: '10px 20px',
backgroundColor: assignmentResult ? (assignmentResult.violations.filter(v =>
v.includes('ERROR:') || v.includes('❌ KRITISCH:')
).length === 0 ? '#2ecc71' : '#95a5a6') : '#95a5a6',
backgroundColor: canPublishAssignment() ? '#2ecc71' : '#95a5a6',
color: 'white',
border: 'none',
borderRadius: '4px',
cursor: assignmentResult ? (assignmentResult.violations.filter(v =>
v.includes('ERROR:') || v.includes('❌ KRITISCH:')
).length === 0 ? 'pointer' : 'not-allowed') : 'not-allowed',
cursor: canPublishAssignment() ? 'pointer' : 'not-allowed',
fontWeight: 'bold',
fontSize: '16px'
}}
>
{publishing ? 'Veröffentliche...' : (
assignmentResult ? (
assignmentResult.violations.filter(v =>
v.includes('ERROR:') || v.includes('❌ KRITISCH:')
).length === 0
canPublishAssignment()
? 'Schichtplan veröffentlichen'
: 'Kritische Probleme müssen behoben werden'
) : 'Lade Zuordnungen...'

View File

@@ -26,7 +26,7 @@ export class ApiClient {
return token ? { 'Authorization': `Bearer ${token}` } : {};
}
private async handleApiResponse<T>(response: Response): Promise<T> {
private async handleApiResponse<T>(response: Response, responseType: 'json' | 'blob' = 'json'): Promise<T> {
if (!response.ok) {
let errorData;
@@ -61,7 +61,12 @@ export class ApiClient {
);
}
// For successful responses, try to parse as JSON
// Handle blob responses (for file downloads)
if (responseType === 'blob') {
return response.blob() as Promise<T>;
}
// For successful JSON responses, try to parse as JSON
try {
const responseText = await response.text();
return responseText ? JSON.parse(responseText) : {} as T;
@@ -71,7 +76,7 @@ export class ApiClient {
}
}
async request<T>(endpoint: string, options: RequestInit = {}): Promise<T> {
async request<T>(endpoint: string, options: RequestInit = {}, responseType: 'json' | 'blob' = 'json'): Promise<T> {
const url = `${this.baseURL}${endpoint}`;
const config: RequestInit = {
@@ -85,7 +90,7 @@ export class ApiClient {
try {
const response = await fetch(url, config);
return await this.handleApiResponse<T>(response);
return await this.handleApiResponse<T>(response, responseType);
} catch (error) {
// Re-throw the error to be caught by useBackendValidation
if (error instanceof ApiError) {

View File

@@ -126,4 +126,60 @@ export const shiftPlanService = {
throw error;
}
},
async exportShiftPlanToExcel(planId: string): Promise<Blob> {
try {
console.log('📊 Exporting shift plan to Excel:', planId);
// Use the apiClient with blob response handling
const blob = await apiClient.request<Blob>(`/shift-plans/${planId}/export/excel`, {
method: 'GET',
}, 'blob');
console.log('✅ Excel export successful');
return blob;
} catch (error: any) {
console.error('❌ Error exporting to Excel:', error);
if (error.statusCode === 401) {
localStorage.removeItem('token');
localStorage.removeItem('employee');
throw new Error('Nicht authorisiert - bitte erneut anmelden');
}
if (error.statusCode === 404) {
throw new Error('Schichtplan nicht gefunden');
}
throw new Error('Fehler beim Excel-Export des Schichtplans');
}
},
async exportShiftPlanToPDF(planId: string): Promise<Blob> {
try {
console.log('📄 Exporting shift plan to PDF:', planId);
// Use the apiClient with blob response handling
const blob = await apiClient.request<Blob>(`/shift-plans/${planId}/export/pdf`, {
method: 'GET',
}, 'blob');
console.log('✅ PDF export successful');
return blob;
} catch (error: any) {
console.error('❌ Error exporting to PDF:', error);
if (error.statusCode === 401) {
localStorage.removeItem('token');
localStorage.removeItem('employee');
throw new Error('Nicht authorisiert - bitte erneut anmelden');
}
if (error.statusCode === 404) {
throw new Error('Schichtplan nicht gefunden');
}
throw new Error('Fehler beim PDF-Export des Schichtplans');
}
},
};