mirror of
https://github.com/donpat1to/Schichtenplaner.git
synced 2025-12-01 15:05:45 +01:00
Compare commits
2 Commits
7c63bee1b3
...
feature/ex
| Author | SHA1 | Date | |
|---|---|---|---|
| 59e326fae3 | |||
| dab5164704 |
@@ -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",
|
||||
|
||||
@@ -19,6 +19,8 @@ export const designTokens = {
|
||||
9: '#cda8f0',
|
||||
10: '#ebd7fa',
|
||||
},
|
||||
|
||||
manager: '#CC0000',
|
||||
|
||||
// Semantic Colors
|
||||
primary: '#51258f',
|
||||
|
||||
@@ -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(
|
||||
@@ -820,9 +896,6 @@ const ShiftPlanView: React.FC = () => {
|
||||
<div style={{ fontSize: '14px', color: '#666' }}>
|
||||
{formatTime(timeSlot.startTime)} - {formatTime(timeSlot.endTime)}
|
||||
</div>
|
||||
<div style={{ fontSize: '11px', color: '#999', marginTop: '4px' }}>
|
||||
ID: {timeSlot.id.substring(0, 8)}...
|
||||
</div>
|
||||
</td>
|
||||
{days.map(weekday => {
|
||||
const shift = timeSlot.shiftsByDay[weekday.id];
|
||||
@@ -846,7 +919,55 @@ const ShiftPlanView: React.FC = () => {
|
||||
const isValidShift = shift.timeSlotId === timeSlot.id && shift.dayOfWeek === weekday.id;
|
||||
|
||||
let assignedEmployees: string[] = [];
|
||||
let displayText = '';
|
||||
let displayContent: React.ReactNode = null;
|
||||
|
||||
// Helper function to create employee boxes
|
||||
const createEmployeeBoxes = (employeeIds: string[]) => {
|
||||
return employeeIds.map(empId => {
|
||||
const employee = employees.find(emp => emp.id === empId);
|
||||
if (!employee) return null;
|
||||
|
||||
// Determine background color based on employee role
|
||||
let backgroundColor = '#642ab5'; // Default: non-trainee personnel (purple)
|
||||
|
||||
if (employee.isTrainee) {
|
||||
backgroundColor = '#cda8f0'; // Trainee
|
||||
} else if (employee.roles?.includes('manager')) {
|
||||
backgroundColor = '#CC0000'; // Manager
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
key={empId}
|
||||
style={{
|
||||
backgroundColor,
|
||||
color: 'white',
|
||||
padding: '4px 8px',
|
||||
borderRadius: '4px',
|
||||
marginBottom: '2px',
|
||||
fontSize: '12px',
|
||||
textAlign: 'center',
|
||||
whiteSpace: 'nowrap',
|
||||
overflow: 'hidden',
|
||||
textOverflow: 'ellipsis'
|
||||
}}
|
||||
title={`${employee.firstname} ${employee.lastname}${employee.isTrainee ? ' (Trainee)' : ''}`}
|
||||
>
|
||||
{employee.firstname} {employee.lastname}
|
||||
</div>
|
||||
);
|
||||
}).filter(Boolean);
|
||||
};
|
||||
|
||||
// Helper function to get fallback content
|
||||
const getFallbackContent = () => {
|
||||
const shiftsForSlot = shiftPlan?.shifts?.filter(s =>
|
||||
s.dayOfWeek === weekday.id &&
|
||||
s.timeSlotId === timeSlot.id
|
||||
) || [];
|
||||
const totalRequired = shiftsForSlot.reduce((sum, s) => sum + s.requiredEmployees, 0);
|
||||
return totalRequired === 0 ? '-' : `0/${totalRequired}`;
|
||||
};
|
||||
|
||||
if (shiftPlan?.status === 'published') {
|
||||
// For published plans, use actual assignments from scheduled shifts
|
||||
@@ -859,15 +980,21 @@ const ShiftPlanView: React.FC = () => {
|
||||
if (scheduledShift) {
|
||||
assignedEmployees = scheduledShift.assignedEmployees || [];
|
||||
|
||||
// DEBUG: Log if we're still seeing old data
|
||||
// Log if we're still seeing old data
|
||||
if (assignedEmployees.length > 0) {
|
||||
console.warn(`⚠️ Found non-empty assignments for ${weekday.name} ${timeSlot.name}:`, assignedEmployees);
|
||||
}
|
||||
|
||||
displayText = assignedEmployees.map(empId => {
|
||||
const employee = employees.find(emp => emp.id === empId);
|
||||
return employee ? `${employee.firstname} ${employee.lastname}` : 'Unbekannt';
|
||||
}).join(', ');
|
||||
const employeeBoxes = createEmployeeBoxes(assignedEmployees);
|
||||
displayContent = employeeBoxes.length > 0 ? (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '2px' }}>
|
||||
{employeeBoxes}
|
||||
</div>
|
||||
) : (
|
||||
<div style={{ color: '#666', fontStyle: 'italic' }}>
|
||||
{getFallbackContent()}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
} else if (assignmentResult) {
|
||||
// For draft with preview, use assignment result
|
||||
@@ -879,30 +1006,26 @@ const ShiftPlanView: React.FC = () => {
|
||||
|
||||
if (scheduledShift) {
|
||||
assignedEmployees = getAssignmentsForScheduledShift(scheduledShift);
|
||||
displayText = assignedEmployees.map(empId => {
|
||||
const employee = employees.find(emp => emp.id === empId);
|
||||
return employee ? `${employee.firstname} ${employee.lastname}` : 'Unbekannt';
|
||||
}).join(', ');
|
||||
const employeeBoxes = createEmployeeBoxes(assignedEmployees);
|
||||
displayContent = employeeBoxes.length > 0 ? (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '2px' }}>
|
||||
{employeeBoxes}
|
||||
</div>
|
||||
) : (
|
||||
<div style={{ color: '#666', fontStyle: 'italic' }}>
|
||||
{getFallbackContent()}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// If no assignments yet, show empty or required count
|
||||
if (!displayText) {
|
||||
const shiftsForSlot = shiftPlan?.shifts?.filter(s =>
|
||||
s.dayOfWeek === weekday.id &&
|
||||
s.timeSlotId === timeSlot.id
|
||||
) || [];
|
||||
|
||||
const totalRequired = shiftsForSlot.reduce((sum, s) =>
|
||||
sum + s.requiredEmployees, 0);
|
||||
|
||||
// Show "0/2" instead of just "0" to indicate it's empty
|
||||
displayText = `0/${totalRequired}`;
|
||||
|
||||
// Optional: Show empty state more clearly
|
||||
if (totalRequired === 0) {
|
||||
displayText = '-';
|
||||
}
|
||||
// If no display content set yet, use fallback
|
||||
if (!displayContent) {
|
||||
displayContent = (
|
||||
<div style={{ color: '#666', fontStyle: 'italic' }}>
|
||||
{getFallbackContent()}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -937,7 +1060,7 @@ const ShiftPlanView: React.FC = () => {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{displayText}
|
||||
{displayContent}
|
||||
|
||||
{/* Shift debug info - SAME AS AVAILABILITYMANAGER */}
|
||||
<div style={{
|
||||
@@ -947,8 +1070,6 @@ const ShiftPlanView: React.FC = () => {
|
||||
textAlign: 'left',
|
||||
fontFamily: 'monospace'
|
||||
}}>
|
||||
<div>Shift: {shift.id.substring(0, 6)}...</div>
|
||||
<div>Day: {shift.dayOfWeek}</div>
|
||||
{!isValidShift && (
|
||||
<div style={{ color: '#e74c3c', fontWeight: 'bold' }}>
|
||||
VALIDATION ERROR
|
||||
@@ -963,7 +1084,6 @@ const ShiftPlanView: React.FC = () => {
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -1005,7 +1125,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>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* "Zuweisungen neu berechnen" button */}
|
||||
{shiftPlan.status === 'published' && hasRole(['admin', 'maintenance']) && (
|
||||
<button
|
||||
onClick={handleRecreateAssignments}
|
||||
disabled={recreating}
|
||||
@@ -1197,15 +1360,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',
|
||||
@@ -1288,32 +1449,24 @@ const ShiftPlanView: React.FC = () => {
|
||||
Abbrechen
|
||||
</button>
|
||||
|
||||
{/* KORRIGIERTER BUTTON MIT TYPESCRIPT-FIX */}
|
||||
{/* BUTTON zum publishen */}
|
||||
<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...'
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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');
|
||||
}
|
||||
},
|
||||
};
|
||||
Reference in New Issue
Block a user