summaryrefslogtreecommitdiff
path: root/calendar_gui.py
blob: f5e015b11f6929fd7a190d819992e90501a3cfe4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
import sys
from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, 
                             QLabel, QLineEdit, QPushButton, QDateEdit, QTableWidget, 
                             QTableWidgetItem, QHeaderView, QDialog, QFormLayout, QComboBox,
                             QMessageBox, QSpinBox, QAction, QFileDialog, QMenuBar, QTextEdit)
from PyQt5.QtCore import Qt, QDate, QLocale
from PyQt5.QtGui import QFont, QFontDatabase
from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta
from calendar_manager import CalendarManager
from date_calculator import DateCalculator
from prediction_controller import PredictionController

DATEFORMAT = "dd.MM.yyyy"

class EventDialog(QDialog):
    def __init__(self, keyword_list, entry=None, parent=None, dateformat: str = DATEFORMAT):
        super().__init__(parent)
        
        self.keyword_list = keyword_list
        self.entry = entry
        self.dateformat = dateformat

        # Set title based on mode
        self.setWindowTitle("Neuer Eintrag" if not entry else "Eintrag editieren")                                                                     
        self.init_ui()
        
    def init_ui(self):
        layout = QFormLayout()
        
        # Apply Arial font
        font = QFont("Arial", 12)
        self.setFont(font) 
        
        # Start date selector
        self.start_date = QDateEdit()
        self.start_date.setCalendarPopup(True)
        self.start_date.setFont(font)
        self.start_date.setDisplayFormat(self.dateformat)
        
        # Set initial date based on mode
        if self.entry:
            entry_start = QDate(self.entry.start_date.year, 
                               self.entry.start_date.month, 
                               self.entry.start_date.day)
            self.start_date.setDate(entry_start)
        else:
            self.start_date.setDate(QDate.currentDate())
                                            
        
        # Connect start date change to validate end date
        self.start_date.dateChanged.connect(self.validate_end_date)
        
        layout.addRow("Startdatum:", self.start_date)
        
        # End date selector
        self.end_date = QDateEdit()
        self.end_date.setCalendarPopup(True)
        self.end_date.setFont(font)
        self.end_date.setDisplayFormat(self.dateformat)
        
        # Set initial date based on mode
        if self.entry:
            entry_end = QDate(self.entry.end_date.year, 
                             self.entry.end_date.month, 
                             self.entry.end_date.day)
            self.end_date.setDate(entry_end)
        else:
            self.end_date.setDate(QDate.currentDate().addDays(1))
        
        layout.addRow("Enddatum:", self.end_date)
        
        # Keyword selector
        self.keyword = QComboBox()
        self.keyword.setFont(font)
        self.keyword.addItems(self.keyword_list)
        
        # Set initial keyword based on mode
        if self.entry and self.entry.keyword in self.keyword_list:
            current_index = self.keyword_list.index(self.entry.keyword)
            self.keyword.setCurrentIndex(current_index)
            
        self.keyword.currentTextChanged.connect(self.on_keyword_changed)
        layout.addRow("Art:", self.keyword)
        
        # Commentary input
        self.commentary_input = QTextEdit()
        self.commentary_input.setFont(font)
        self.commentary_input.setFixedHeight(80)
        if self.entry and hasattr(self.entry, 'commentary') and self.entry.commentary:
            self.commentary_input.setPlainText(self.entry.commentary)
        layout.addRow("Kommentar:", self.commentary_input)
        
        # Store layout for later access
        self.layout = layout
        self.end_date_row = 1  # Index of end date row in the form layout
        
        # Buttons
        button_layout = QHBoxLayout()
        self.save_button = QPushButton("Speichern")
        self.save_button.setFont(font)
        self.save_button.clicked.connect(self.accept)
        
        self.cancel_button = QPushButton("Abbrechen")
        self.cancel_button.setFont(font)
        self.cancel_button.clicked.connect(self.reject)
        
        button_layout.addWidget(self.save_button)
        button_layout.addWidget(self.cancel_button)
        layout.addRow("", button_layout)
        
        self.setLayout(layout)
        
        # Handle initial keyword selection
        self.on_keyword_changed(self.keyword.currentText())
        
    def on_keyword_changed(self, keyword):
        """Handle visibility of the end_date field based on keyword"""
        # Get the widgets from the form layout
        end_date_label = self.layout.itemAt(self.end_date_row, QFormLayout.LabelRole).widget()
        end_date_field = self.layout.itemAt(self.end_date_row, QFormLayout.FieldRole).widget()
        
        if keyword == "EZ pauschal":
            # Hide end date field for EZ pauschals since they have fixed 4-week duration
            end_date_label.setVisible(False)
            end_date_field.setVisible(False)
            
            # Update end date automatically if changing to EZ pauschal
            start_dt = self.start_date.date().toPyDate()
            end_dt = start_dt + relativedelta(years = 2, days = -1)
            self.end_date.setDate(QDate(end_dt.year, end_dt.month, end_dt.day))
        else:
            # Show end date field for other event types
            end_date_label.setVisible(True)
            end_date_field.setVisible(True)
            
    def validate_end_date(self):
        """Ensure end date is not before start date"""
        if self.end_date.date() < self.start_date.date():
            self.end_date.setDate(self.start_date.date())
    def get_data(self):
        start_date = self.start_date.date().toString("yyyy-MM-dd")
        keyword = self.keyword.currentText()
        commentary = self.commentary_input.toPlainText().strip()
        
        if keyword == "EZ pauschal":
            # For EZ pauschals, calculate end date as start + 4 weeks
            start_dt = datetime.fromisoformat(start_date)
            end_dt = start_dt + relativedelta(years = 2, days = -1)
            end_date = end_dt.strftime("%Y-%m-%d")
        else:
            end_date = self.end_date.date().toString("yyyy-MM-dd")
        return start_date, end_date, keyword, commentary


class CalendarManagerGUI(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Ausfallzeitenrechner")
        self.setMinimumSize(800, 600)
        
        # Set application font
        self.app_font = QFont("Arial", 12)
        QApplication.setFont(self.app_font)
        
        # Get system locale for consistent date formatting
        self.locale = QLocale.system()
        self.dateformat = DATEFORMAT
        
        # Initialize backend components
        self.keyword_list = ["EZ 100%", "EZ 50%", "EZ pauschal", "Sonstige"]
        self.calendar_manager = CalendarManager()
        self.date_calculator = DateCalculator()
        self.prediction_controller = PredictionController(
            self.calendar_manager, 
            self.date_calculator, 
            self.keyword_list
        )
        
        self.init_ui()
        self.create_menus()
        
    def create_menus(self):
        # Create menu bar
        menubar = self.menuBar()
        menubar.setFont(self.app_font)
        
        # File menu
        file_menu = menubar.addMenu('Start')
        
        # Save action
        save_action = QAction('Speichern', self)
        save_action.setShortcut('Ctrl+S')
        save_action.triggered.connect(self.save_file)
        file_menu.addAction(save_action)
        
        # Load action
        load_action = QAction('Laden', self)
        load_action.setShortcut('Ctrl+L')
        load_action.triggered.connect(self.load_file)
        file_menu.addAction(load_action)
        
        # Clear action
        clear_action = QAction('Einträge löschen', self)
        clear_action.setShortcut('Ctrl+N')
        clear_action.triggered.connect(self.clear_entries)
        file_menu.addAction(clear_action)
        
        # Exit action
        exit_action = QAction('Beenden', self)
        exit_action.setShortcut('Ctrl+Q')
        exit_action.triggered.connect(self.close)
        file_menu.addAction(exit_action)
        
    def init_ui(self):        
        central_widget = QWidget()
        main_layout = QVBoxLayout()
        
        top_layout = QHBoxLayout()
        
        # Launch date input
        launch_date_layout = QVBoxLayout()
        launch_date_label = QLabel("Promotionsdatum:")
        launch_date_label.setFont(self.app_font)
        self.launch_date_edit = QDateEdit()
        self.launch_date_edit.setFont(self.app_font)
        self.launch_date_edit.setCalendarPopup(True)  # Enable calendar popup
        self.launch_date_edit.setDate(QDate.currentDate())
        self.launch_date_edit.setDisplayFormat(self.dateformat)
        self.launch_date_edit.dateChanged.connect(self.update_prediction)  # Auto-update on change
        launch_date_layout.addWidget(launch_date_label)
        launch_date_layout.addWidget(self.launch_date_edit)
        top_layout.addLayout(launch_date_layout)
        
        # Duration input
        duration_layout = QVBoxLayout()
        duration_label = QLabel("Bewerbungszeitraum (Jahre):")
        duration_label.setFont(self.app_font)
        self.duration_spin = QSpinBox()
        self.duration_spin.setFont(self.app_font)
        self.duration_spin.setRange(1, 99)
        self.duration_spin.setValue(1)
        self.duration_spin.valueChanged.connect(self.update_prediction)  # Auto-update on change
        duration_layout.addWidget(duration_label)
        duration_layout.addWidget(self.duration_spin)
        top_layout.addLayout(duration_layout)
        
        # Prediction result
        prediction_result_layout = QVBoxLayout()
        prediction_result_label = QLabel("Bewerbungsfrist:")
        prediction_result_label.setFont(self.app_font)
        self.prediction_result = QDateEdit()
        self.prediction_result.setFont(self.app_font)
        self.prediction_result.setReadOnly(True)
        self.prediction_result.setButtonSymbols(QDateEdit.ButtonSymbols.NoButtons)
        self.prediction_result.setDisplayFormat(self.dateformat)
        prediction_result_layout.addWidget(prediction_result_label)
        prediction_result_layout.addWidget(self.prediction_result)
        
        top_layout.addLayout(prediction_result_layout)
        
        main_layout.addLayout(top_layout)
        
        # Events section
        events_layout = QVBoxLayout()
        events_title = QLabel("<h3>Ausfallzeiten</h3>")
        events_title.setFont(self.app_font)
        events_layout.addWidget(events_title)
        
        # Add event button
        add_event_button = QPushButton("Eintrag hinzufügen")
        add_event_button.setFont(self.app_font)
        add_event_button.clicked.connect(self.add_event)
        events_layout.addWidget(add_event_button)
        
        # Events table
        self.events_table = QTableWidget()
        self.events_table.setFont(self.app_font)
        self.events_table.setColumnCount(7)  # ID (hidden), Start, End, Keyword, RelevantTime, Commentary, Actions
        self.events_table.setHorizontalHeaderLabels(["ID", "Anfangsdatum", "Enddatum", "Art", "Angerechneter Zeitraum", "Kommentar", "Aktionen"])
        self.events_table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.events_table.horizontalHeader().setFont(self.app_font)
        self.events_table.setColumnHidden(0, True)  # Hide ID column
        events_layout.addWidget(self.events_table)
        
        main_layout.addLayout(events_layout)
        
        # Set main layout
        central_widget.setLayout(main_layout)
        self.setCentralWidget(central_widget)
        
        # Load initial data
        self.update_events_table()
        self.update_prediction()  # Calculate initial prediction
    
    def update_prediction(self):
        """Update prediction whenever needed"""
        try:
            launch_date = self.launch_date_edit.date().toString("yyyy-MM-dd")
            duration_years = self.duration_spin.value()
            
            self.prediction_controller.make_prediction(launch_date, duration_years)
            prediction_date = self.prediction_controller.get_prediction()
            
            if prediction_date:
                self.prediction_result.setDate(prediction_date)
                
            # Update table to show corrected dates
            self.update_events_table()
            
        except Exception as e:
            self.prediction_result.setText("Error in calculation")
            print(f"Error calculating prediction: {str(e)}")
    
    def add_event(self):
        dialog = EventDialog(self.keyword_list, parent=self, dateformat=self.dateformat)
        if dialog.exec_():
            start_date, end_date, keyword, commentary = dialog.get_data()
            try:
                self.calendar_manager.add_entry(start_date, end_date, keyword, commentary)
                self.update_events_table()
                self.update_prediction()  # Auto-update prediction
            except Exception as e:
                QMessageBox.critical(self, "Error", f"Error adding event: {str(e)}")
    
    def modify_event(self, event_id):
        entry = self.calendar_manager.get_entry_by_id(event_id)
        if entry:
            dialog = EventDialog(self.keyword_list, entry=entry, parent=self, dateformat=self.dateformat)
            if dialog.exec_():
                start_date, end_date, keyword, commentary = dialog.get_data()
                try:
                    self.calendar_manager.modify_entry(event_id, 
                                                     datetime.fromisoformat(start_date), 
                                                     datetime.fromisoformat(end_date), 
                                                     keyword,
                                                     commentary)
                    self.update_events_table()
                    self.update_prediction()  # Auto-update prediction
                except Exception as e:
                    QMessageBox.critical(self, "Error", f"Error modifying event: {str(e)}")
    
    def delete_event(self, event_id):
        reply = QMessageBox.question(self, "Eintrag löschen", 
                                     "Wollen Sie diesen Eintrag löschen?",
                                     QMessageBox.Yes | QMessageBox.No)
        if reply == QMessageBox.Yes:
            try:
                self.calendar_manager.delete_entry(event_id)
                self.update_events_table()
                self.update_prediction()  # Auto-update prediction
            except Exception as e:
                QMessageBox.critical(self, "Error", f"Error deleting event: {str(e)}")
    
    def update_events_table(self):
        # Clear table
        self.events_table.setRowCount(0)
        
        # Add entries to table
        entries = self.calendar_manager.list_entries()
        for i, entry in enumerate(entries):
            self.events_table.insertRow(i)
            
            # Set item data
            self.events_table.setItem(i, 0, QTableWidgetItem(entry.id))
            
            # Format dates using unified display format
            start_date_qdate = QDate(entry.start_date.year, entry.start_date.month, entry.start_date.day)
            end_date_qdate = QDate(entry.end_date.year, entry.end_date.month, entry.end_date.day)
            
            start_date_text = start_date_qdate.toString(self.dateformat)
            end_date_text = end_date_qdate.toString(self.dateformat)
            self.events_table.setItem(i, 1, QTableWidgetItem(start_date_text))
            self.events_table.setItem(i, 2, QTableWidgetItem(end_date_text))
            self.events_table.setItem(i, 3, QTableWidgetItem(entry.keyword))
            
            # Relevant accounted time based on corrected dates
            relevant_text = ""
            if entry.corrected_start_date and entry.corrected_end_date:
                start_dt = entry.corrected_start_date
                end_dt = entry.corrected_end_date
                if end_dt < start_dt:
                    start_dt, end_dt = end_dt, start_dt
                delta_days = (end_dt.date() - start_dt.date()).days + 1
                # Determine if less than 3 months using relativedelta
                rd = relativedelta(end_dt.date(), start_dt.date())
                total_months = rd.years * 12 + rd.months
                if total_months < 3:
                    relevant_text = f"{delta_days} Tage"
                else:
                    # Months and remaining days
                    # Compute month/day split precisely
                    month_start = start_dt.date()
                    month_split = month_start + relativedelta(months=+total_months)
                    remaining_days = (end_dt.date() - month_split).days + 1 if end_dt.date() >= month_split else delta_days
                    relevant_text = f"{total_months} Monate, {max(0, remaining_days)} Tage"
            self.events_table.setItem(i, 4, QTableWidgetItem(relevant_text))

            # Commentary
            commentary_text = getattr(entry, 'commentary', "") or ""
            self.events_table.setItem(i, 5, QTableWidgetItem(commentary_text))
            
            # Action buttons
            actions_widget = QWidget()
            actions_layout = QHBoxLayout()
            actions_layout.setContentsMargins(0, 0, 0, 0)
            
            modify_button = QPushButton("Editieren")
            modify_button.setFont(self.app_font)
            delete_button = QPushButton("Löschen")
            delete_button.setFont(self.app_font)
            
            # Use lambda with default argument to capture the correct event_id
            modify_button.clicked.connect(lambda checked, eid=entry.id: self.modify_event(eid))
            delete_button.clicked.connect(lambda checked, eid=entry.id: self.delete_event(eid))
            
            actions_layout.addWidget(modify_button)
            actions_layout.addWidget(delete_button)
            actions_widget.setLayout(actions_layout)
            
            self.events_table.setCellWidget(i, 6, actions_widget)
    
    def save_file(self):
        """Save calendar entries to a JSON file"""
        # if not self.calendar_manager.filename:
        file_path, _ = QFileDialog.getSaveFileName(self, "Einträge speichern", "", "JSON Files (*.json)")
        if not file_path:
            return
        self.calendar_manager.switch_file(file_path)
            
        try:
            self.calendar_manager.save_entries()
            QMessageBox.information(self, "Speichern erfolgreich", f"Einträge gespeichert in {self.calendar_manager.filename}")
        except Exception as e:
            QMessageBox.critical(self, "Error", f"Failed to save calendar: {str(e)}")
    
    def load_file(self):
        """Load calendar entries from a JSON file"""
        file_path, _ = QFileDialog.getOpenFileName(self, "Einträge laden", "", "JSON Files (*.json)")
        if not file_path:
            return
            
        try:
            self.calendar_manager.load_file(file_path)
            self.update_events_table()
            self.update_prediction()  # Auto-update prediction
            QMessageBox.information(self, "Laden erfolgreich", f"Einträge erfolgreich von {file_path} geladen")
        except Exception as e:
            QMessageBox.critical(self, "Error", f"Failed to load calendar: {str(e)}")
    
    def clear_entries(self):
        """Clear all calendar entries"""
        reply = QMessageBox.question(self, "Einträge löschen", 
                                    "Alle Einträge löschen?",
                                    QMessageBox.Yes | QMessageBox.No)
        if reply == QMessageBox.Yes:
            try:
                self.calendar_manager.clear_entries()
                self.update_events_table()
                self.update_prediction()  # Auto-update prediction
                QMessageBox.information(self, "Erfolg", "Alle Einträge gelöscht!")
            except Exception as e:
                QMessageBox.critical(self, "Error", f"Failed to clear calendar: {str(e)}")


def main():
    app = QApplication(sys.argv)
    app.setStyle('Fusion')
    # Ensure Arial is available
    QFontDatabase.addApplicationFont("Arial")
    window = CalendarManagerGUI()
    window.show()
    sys.exit(app.exec_())


if __name__ == "__main__":
    main()