-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfee_tracker.py
More file actions
3124 lines (2632 loc) · 125 KB
/
Copy pathfee_tracker.py
File metadata and controls
3124 lines (2632 loc) · 125 KB
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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Music Class Fee Tracker
A GUI application to categorize and track student fees from bank statements
"""
import sys
import re
import json
import copy
from datetime import datetime
from pathlib import Path
from PySide6.QtWidgets import (
QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
QPushButton, QTableWidget, QTableWidgetItem, QFileDialog,
QLabel, QGroupBox, QHeaderView, QMessageBox, QLineEdit, QComboBox,
QDialog, QFormLayout, QDialogButtonBox, QDoubleSpinBox, QGridLayout,
QCheckBox, QDateEdit, QListWidget, QListWidgetItem
)
from PySide6.QtCore import Qt, QTimer, QDate
from PySide6.QtGui import QFont, QColor
# Import student name mappings
from student_mappings import get_full_name
class EditTransactionDialog(QDialog):
"""Dialog for editing a transaction"""
def __init__(self, transaction, available_categories, parent=None):
super().__init__(parent)
self.transaction = transaction
self.available_categories = available_categories
self.setWindowTitle("Edit Transaction")
self.setModal(True)
self.init_ui()
def init_ui(self):
"""Initialize the dialog UI"""
layout = QFormLayout(self)
# Name field (editable)
self.name_input = QLineEdit(self.transaction['name'])
layout.addRow("Name:", self.name_input)
# Date field (editable)
self.date_edit = QDateEdit()
self.date_edit.setCalendarPopup(True)
self.date_edit.setDisplayFormat("dd-MM-yyyy")
# Parse the date from the transaction (format can be DD-MM-YYYY HH:MM:SS or DD-MM-YYYY or DD/MM/YYYY)
date_str = self.transaction['date']
# Remove time component if present
if ' ' in date_str:
date_str = date_str.split(' ')[0]
# Try splitting by hyphen first (the actual format from CSV)
date_parts = date_str.split('-')
if len(date_parts) != 3:
# Try splitting by slash as fallback
date_parts = date_str.split('/')
if len(date_parts) == 3:
try:
day, month, year = date_parts
self.date_edit.setDate(QDate(int(year), int(month), int(day)))
except ValueError:
# If parsing fails, use current date
self.date_edit.setDate(QDate.currentDate())
else:
# If format is unexpected, use current date
self.date_edit.setDate(QDate.currentDate())
layout.addRow("Date:", self.date_edit)
# Amount field (editable)
self.amount_spinbox = QDoubleSpinBox()
self.amount_spinbox.setRange(0, 999999)
self.amount_spinbox.setDecimals(2)
self.amount_spinbox.setValue(self.transaction['amount'])
self.amount_spinbox.setPrefix("₹")
layout.addRow("Amount:", self.amount_spinbox)
# Category field (editable)
self.category_combo = QComboBox()
self.category_combo.addItems(self.available_categories)
self.category_combo.setCurrentText(self.transaction['category'])
layout.addRow("Category:", self.category_combo)
# Dialog buttons
buttons = QDialogButtonBox(
QDialogButtonBox.Ok | QDialogButtonBox.Cancel
)
buttons.accepted.connect(self.accept)
buttons.rejected.connect(self.reject)
layout.addRow(buttons)
def get_updated_transaction(self):
"""Return the updated transaction data"""
# Format date back to DD-MM-YYYY (matching the original CSV format)
# Preserve the time component if it exists in the original
date = self.date_edit.date()
formatted_date = date.toString("dd-MM-yyyy")
# If original date had time component, append it back
original_date = self.transaction['date']
if ' ' in original_date:
time_component = ' '.join(original_date.split(' ')[1:])
formatted_date = f"{formatted_date} {time_component}"
return {
**self.transaction,
'name': self.name_input.text(),
'date': formatted_date,
'amount': self.amount_spinbox.value(),
'category': self.category_combo.currentText()
}
class CategoryManagerDialog(QDialog):
"""Dialog for managing fee categories"""
def __init__(self, categories, parent=None):
super().__init__(parent)
self.categories = copy.deepcopy(categories) # Deep copy to avoid reference issues
self.setWindowTitle("Manage Categories")
self.setModal(True)
self.setMinimumSize(600, 400)
self.init_ui()
def init_ui(self):
"""Initialize the category manager UI"""
layout = QVBoxLayout(self)
# Title
title_label = QLabel("📂 Category Management")
title_font = QFont()
title_font.setPointSize(16)
title_font.setBold(True)
title_label.setFont(title_font)
title_label.setAlignment(Qt.AlignCenter)
layout.addWidget(title_label)
# Instructions
info_label = QLabel("Add, edit, or delete fee categories. Categories with fixed amounts will auto-categorize transactions.")
info_label.setWordWrap(True)
info_label.setStyleSheet("color: #666; padding: 10px; background-color: #f5f5f5; border-radius: 5px;")
layout.addWidget(info_label)
# Main content area
content_layout = QHBoxLayout()
# Left side - Category list
left_layout = QVBoxLayout()
left_layout.addWidget(QLabel("Existing Categories:"))
self.category_list = QListWidget()
self.category_list.setMinimumWidth(300)
self.update_category_list()
self.category_list.itemSelectionChanged.connect(self.on_category_selected)
left_layout.addWidget(self.category_list)
# List buttons
list_btn_layout = QHBoxLayout()
self.delete_btn = QPushButton("🗑️ Delete")
self.delete_btn.setEnabled(False)
self.delete_btn.setStyleSheet("""
QPushButton {
background-color: #f44336;
color: white;
padding: 5px 15px;
border-radius: 3px;
}
QPushButton:hover:enabled {
background-color: #d32f2f;
}
QPushButton:disabled {
background-color: #ccc;
}
""")
self.delete_btn.clicked.connect(self.delete_category)
list_btn_layout.addWidget(self.delete_btn)
list_btn_layout.addStretch()
left_layout.addLayout(list_btn_layout)
content_layout.addLayout(left_layout)
# Right side - Add/Edit form
right_layout = QVBoxLayout()
form_label = QLabel("Add/Edit Category:")
form_label.setStyleSheet("font-weight: bold; font-size: 13px; color: #333;")
right_layout.addWidget(form_label)
form_widget = QWidget()
form_widget.setStyleSheet("background-color: #fafafa; border: 1px solid #ddd; border-radius: 5px;")
form_layout = QFormLayout(form_widget)
# Category name
self.name_input = QLineEdit()
self.name_input.setPlaceholderText("e.g., Piano Lessons")
self.name_input.setStyleSheet("""
QLineEdit {
background-color: white;
color: #000;
padding: 8px;
border: 2px solid #ccc;
border-radius: 4px;
font-size: 13px;
}
QLineEdit:focus {
border: 2px solid #2196F3;
}
""")
name_label = QLabel("Category Name:")
name_label.setStyleSheet("color: #333; font-weight: bold;")
form_layout.addRow(name_label, self.name_input)
# Fee amount
self.fee_input = QDoubleSpinBox()
self.fee_input.setRange(0, 999999)
self.fee_input.setDecimals(2)
self.fee_input.setValue(500.0)
self.fee_input.setPrefix("₹")
self.fee_input.setSpecialValueText("Variable Amount")
self.fee_input.setStyleSheet("""
QDoubleSpinBox {
background-color: white;
color: #000;
padding: 8px;
border: 2px solid #ccc;
border-radius: 4px;
font-size: 13px;
}
QDoubleSpinBox:focus {
border: 2px solid #2196F3;
}
""")
fee_label = QLabel("Fixed Amount:")
fee_label.setStyleSheet("color: #333; font-weight: bold;")
form_layout.addRow(fee_label, self.fee_input)
# Help text
help_text = QLabel("💡 Set amount to 0 for variable amounts (donations, etc.)")
help_text.setStyleSheet("color: #666; font-size: 11px; padding: 5px;")
form_layout.addRow("", help_text)
right_layout.addWidget(form_widget)
# Form buttons
form_btn_layout = QHBoxLayout()
self.add_btn = QPushButton("➕ Add Category")
self.add_btn.setStyleSheet("""
QPushButton {
background-color: #4CAF50;
color: white;
padding: 8px 20px;
border-radius: 5px;
font-weight: bold;
}
QPushButton:hover {
background-color: #45a049;
}
""")
self.add_btn.clicked.connect(self.add_category)
form_btn_layout.addWidget(self.add_btn)
self.update_btn = QPushButton("✏️ Update Category")
self.update_btn.setEnabled(False)
self.update_btn.setStyleSheet("""
QPushButton {
background-color: #FF9800;
color: white;
padding: 8px 20px;
border-radius: 5px;
font-weight: bold;
}
QPushButton:hover:enabled {
background-color: #F57C00;
}
QPushButton:disabled {
background-color: #ccc;
}
""")
self.update_btn.clicked.connect(self.update_category)
form_btn_layout.addWidget(self.update_btn)
self.clear_btn = QPushButton("🔄 Clear")
self.clear_btn.setStyleSheet("""
QPushButton {
background-color: #757575;
color: white;
padding: 8px 20px;
border-radius: 5px;
}
QPushButton:hover {
background-color: #616161;
}
""")
self.clear_btn.clicked.connect(self.clear_form)
form_btn_layout.addWidget(self.clear_btn)
right_layout.addLayout(form_btn_layout)
right_layout.addStretch()
content_layout.addLayout(right_layout)
layout.addLayout(content_layout)
# Dialog buttons
button_layout = QHBoxLayout()
button_layout.addStretch()
self.save_btn = QPushButton("💾 Save")
self.save_btn.setStyleSheet("""
QPushButton {
background-color: #2196F3;
color: white;
padding: 10px 30px;
border-radius: 5px;
font-weight: bold;
}
QPushButton:hover {
background-color: #1976D2;
}
""")
self.save_btn.clicked.connect(self.accept)
button_layout.addWidget(self.save_btn)
cancel_btn = QPushButton("❌ Cancel")
cancel_btn.setStyleSheet("""
QPushButton {
background-color: #757575;
color: white;
padding: 10px 30px;
border-radius: 5px;
}
QPushButton:hover {
background-color: #616161;
}
""")
cancel_btn.clicked.connect(self.reject)
button_layout.addWidget(cancel_btn)
layout.addLayout(button_layout)
def update_category_list(self):
"""Update the category list display"""
self.category_list.clear()
# Create font for category items
item_font = QFont()
item_font.setPointSize(14)
for category in self.categories:
if category['fee'] is None or category['fee'] == 0:
text = f"📊 {category['name']} (Variable Amount)"
else:
text = f"💰 {category['name']} (₹{category['fee']:.0f})"
item = QListWidgetItem(text)
item.setFont(item_font)
item.setData(Qt.UserRole, category)
self.category_list.addItem(item)
def on_category_selected(self):
"""Handle category selection"""
current_item = self.category_list.currentItem()
if current_item:
category = current_item.data(Qt.UserRole)
self.name_input.setText(category['name'])
self.fee_input.setValue(category['fee'] if category['fee'] is not None else 0)
self.delete_btn.setEnabled(True)
self.update_btn.setEnabled(True)
self.add_btn.setText("➕ Add New Category")
else:
self.delete_btn.setEnabled(False)
self.update_btn.setEnabled(False)
def add_category(self):
"""Add a new category"""
name = self.name_input.text().strip()
fee = self.fee_input.value()
if not name:
QMessageBox.warning(self, "Invalid Input", "Please enter a category name.")
return
# Check for duplicate names
if any(cat['name'].lower() == name.lower() for cat in self.categories):
QMessageBox.warning(self, "Duplicate Category", f"Category '{name}' already exists.")
return
# Check for duplicate variable amount categories (fee = 0 or null)
if fee == 0:
existing_variable = next((cat for cat in self.categories if cat['fee'] is None or cat['fee'] == 0), None)
if existing_variable:
QMessageBox.warning(
self,
"Variable Amount Exists",
f"A variable amount category '{existing_variable['name']}' already exists.\n\n"
f"You can only have one variable amount category for miscellaneous/donation transactions.\n"
f"Please use a fixed amount instead or edit the existing variable category."
)
return
# Check for duplicate fee amounts (only for non-zero fees)
if fee > 0:
existing_category = next((cat for cat in self.categories if cat['fee'] == fee), None)
if existing_category:
QMessageBox.warning(
self,
"Duplicate Amount",
f"Amount ₹{fee:.0f} is already used by '{existing_category['name']}'.\n\n"
f"Each category must have a unique fixed amount for proper auto-categorization.\n"
f"Please use a different amount or set to 0 for variable amounts."
)
return
# Add category
new_category = {
'name': name,
'fee': fee if fee > 0 else None
}
self.categories.append(new_category)
self.update_category_list()
self.clear_form()
QMessageBox.information(self, "Success", f"Category '{name}' added successfully!")
def update_category(self):
"""Update selected category"""
current_item = self.category_list.currentItem()
if not current_item:
return
name = self.name_input.text().strip()
fee = self.fee_input.value()
if not name:
QMessageBox.warning(self, "Invalid Input", "Please enter a category name.")
return
# Get selected category from the list item
selected_category = current_item.data(Qt.UserRole)
old_name = selected_category['name']
# Find the actual category in self.categories list by matching the old values
category_to_update = None
for cat in self.categories:
if cat['name'] == old_name and cat['fee'] == selected_category['fee']:
category_to_update = cat
break
if not category_to_update:
QMessageBox.warning(self, "Error", "Could not find category to update.")
return
# Check for duplicate names (excluding current)
if any(cat['name'].lower() == name.lower() and cat is not category_to_update for cat in self.categories):
QMessageBox.warning(self, "Duplicate Category", f"Category '{name}' already exists.")
return
# Check for duplicate variable amount categories (excluding current)
if fee == 0:
existing_variable = next((cat for cat in self.categories if (cat['fee'] is None or cat['fee'] == 0) and cat is not category_to_update), None)
if existing_variable:
QMessageBox.warning(
self,
"Variable Amount Exists",
f"A variable amount category '{existing_variable['name']}' already exists.\n\n"
f"You can only have one variable amount category for miscellaneous/donation transactions.\n"
f"Please use a fixed amount instead or edit the existing variable category."
)
return
# Check for duplicate fee amounts (only for non-zero fees, excluding current)
if fee > 0:
existing_category = next((cat for cat in self.categories if cat['fee'] == fee and cat is not category_to_update), None)
if existing_category:
QMessageBox.warning(
self,
"Duplicate Amount",
f"Amount ₹{fee:.0f} is already used by '{existing_category['name']}'.\n\n"
f"Each category must have a unique fixed amount for proper auto-categorization.\n"
f"Please use a different amount or set to 0 for variable amounts."
)
return
# Update the category in the list
category_to_update['name'] = name
category_to_update['fee'] = fee if fee > 0 else None
# Refresh the list display
self.update_category_list()
self.clear_form()
QMessageBox.information(self, "Success", f"Category updated from '{old_name}' to '{name}'!")
def delete_category(self):
"""Delete selected category"""
current_item = self.category_list.currentItem()
if not current_item:
return
category = current_item.data(Qt.UserRole)
reply = QMessageBox.question(
self,
"Confirm Deletion",
f"Are you sure you want to delete the category '{category['name']}'?\n\n"
f"This action cannot be undone.",
QMessageBox.Yes | QMessageBox.No,
QMessageBox.No
)
if reply == QMessageBox.Yes:
self.categories.remove(category)
self.update_category_list()
self.clear_form()
QMessageBox.information(self, "Deleted", f"Category '{category['name']}' deleted successfully!")
def clear_form(self):
"""Clear the form inputs"""
self.name_input.clear()
self.fee_input.setValue(500.0)
self.category_list.clearSelection()
self.delete_btn.setEnabled(False)
self.update_btn.setEnabled(False)
self.add_btn.setText("➕ Add Category")
def get_categories(self):
"""Return the updated categories"""
return self.categories
class StudentManagerDialog(QDialog):
"""Dialog for managing student name mappings"""
def __init__(self, parent=None):
super().__init__(parent)
from student_mappings import get_all_mappings, save_student_mappings
self.get_all_mappings = get_all_mappings
self.save_student_mappings = save_student_mappings
self.mappings = get_all_mappings()
self.setWindowTitle("Manage Student Names")
self.setModal(True)
self.setMinimumSize(800, 600)
self.init_ui()
def init_ui(self):
"""Initialize the student manager UI"""
layout = QVBoxLayout(self)
# Title
title_label = QLabel("👥 Student Name Management")
title_font = QFont()
title_font.setPointSize(16)
title_font.setBold(True)
title_label.setFont(title_font)
title_label.setAlignment(Qt.AlignCenter)
layout.addWidget(title_label)
# Instructions
info_label = QLabel(
"Manage student name mappings. Upload a CSV/Excel file with two columns:\n"
"Column 1: Short Name (from bank statement), Column 2: Full Student Name"
)
info_label.setWordWrap(True)
info_label.setStyleSheet("color: #666; padding: 10px; background-color: #f5f5f5; border-radius: 5px;")
layout.addWidget(info_label)
# Button row
btn_layout = QHBoxLayout()
upload_csv_btn = QPushButton("📁 Import from CSV")
upload_csv_btn.setStyleSheet("""
QPushButton {
background-color: #4CAF50;
color: white;
padding: 8px 20px;
border-radius: 5px;
font-weight: bold;
}
QPushButton:hover {
background-color: #45a049;
}
""")
upload_csv_btn.clicked.connect(self.import_from_csv)
btn_layout.addWidget(upload_csv_btn)
upload_excel_btn = QPushButton("📊 Import from Excel")
upload_excel_btn.setStyleSheet("""
QPushButton {
background-color: #2196F3;
color: white;
padding: 8px 20px;
border-radius: 5px;
font-weight: bold;
}
QPushButton:hover {
background-color: #0b7dda;
}
""")
upload_excel_btn.clicked.connect(self.import_from_excel)
btn_layout.addWidget(upload_excel_btn)
export_btn = QPushButton("💾 Export to Excel")
export_btn.setStyleSheet("""
QPushButton {
background-color: #FF9800;
color: white;
padding: 8px 20px;
border-radius: 5px;
font-weight: bold;
}
QPushButton:hover {
background-color: #F57C00;
}
""")
export_btn.clicked.connect(self.export_to_excel)
btn_layout.addWidget(export_btn)
# Add student button
add_student_btn = QPushButton("➕ Add Student")
add_student_btn.setStyleSheet("""
QPushButton {
background-color: #4CAF50;
color: white;
padding: 8px 20px;
border-radius: 5px;
font-weight: bold;
}
QPushButton:hover {
background-color: #45a049;
}
""")
add_student_btn.clicked.connect(self.add_student)
btn_layout.addWidget(add_student_btn)
btn_layout.addStretch()
layout.addLayout(btn_layout)
# Search box
search_layout = QHBoxLayout()
search_label = QLabel("🔍 Search:")
search_label.setStyleSheet("font-weight: bold;")
search_layout.addWidget(search_label)
self.search_input = QLineEdit()
self.search_input.setPlaceholderText("Search by short name or full name...")
self.search_input.setStyleSheet("""
QLineEdit {
padding: 8px;
border: 2px solid #ccc;
border-radius: 5px;
font-size: 13px;
}
QLineEdit:focus {
border: 2px solid #2196F3;
}
""")
self.search_input.textChanged.connect(self.filter_table)
search_layout.addWidget(self.search_input)
clear_search_btn = QPushButton("✕ Clear")
clear_search_btn.setStyleSheet("""
QPushButton {
background-color: #757575;
color: white;
padding: 8px 15px;
border-radius: 5px;
}
QPushButton:hover {
background-color: #616161;
}
""")
clear_search_btn.clicked.connect(self.clear_search)
search_layout.addWidget(clear_search_btn)
layout.addLayout(search_layout)
# Student list table
self.table = QTableWidget()
self.table.setColumnCount(4)
self.table.setHorizontalHeaderLabels(["Short Name", "Full Student Name", "Edit", "Delete"])
header = self.table.horizontalHeader()
header.setSectionResizeMode(0, QHeaderView.ResizeToContents)
header.setSectionResizeMode(1, QHeaderView.Stretch)
header.setSectionResizeMode(2, QHeaderView.ResizeToContents)
header.setSectionResizeMode(3, QHeaderView.ResizeToContents)
self.table.setAlternatingRowColors(True)
layout.addWidget(self.table)
# Count label (must be created before calling update_table)
self.count_label = QLabel(f"Total Students: {len(self.mappings)}")
self.count_label.setStyleSheet("font-weight: bold; color: #1976D2; padding: 5px;")
layout.addWidget(self.count_label)
# Now populate the table
self.update_table()
# Dialog buttons
button_layout = QHBoxLayout()
button_layout.addStretch()
save_btn = QPushButton("💾 Save Changes")
save_btn.setStyleSheet("""
QPushButton {
background-color: #4CAF50;
color: white;
padding: 10px 30px;
border-radius: 5px;
font-weight: bold;
}
QPushButton:hover {
background-color: #45a049;
}
""")
save_btn.clicked.connect(self.save_and_close)
button_layout.addWidget(save_btn)
cancel_btn = QPushButton("❌ Cancel")
cancel_btn.setStyleSheet("""
QPushButton {
background-color: #757575;
color: white;
padding: 10px 30px;
border-radius: 5px;
}
QPushButton:hover {
background-color: #616161;
}
""")
cancel_btn.clicked.connect(self.reject)
button_layout.addWidget(cancel_btn)
layout.addLayout(button_layout)
def update_table(self):
"""Update the student table display"""
self.table.setRowCount(len(self.mappings))
for row, (short_name, full_name) in enumerate(sorted(self.mappings.items())):
# Short name
short_item = QTableWidgetItem(short_name)
short_item.setFlags(short_item.flags() & ~Qt.ItemIsEditable)
self.table.setItem(row, 0, short_item)
# Full name (editable)
full_item = QTableWidgetItem(full_name)
self.table.setItem(row, 1, full_item)
# Edit button
edit_btn = QPushButton("✏️ Edit")
edit_btn.setStyleSheet("""
QPushButton {
background-color: #2196F3;
color: white;
padding: 4px 10px;
border-radius: 3px;
}
QPushButton:hover {
background-color: #1976D2;
}
""")
edit_btn.clicked.connect(lambda checked, sn=short_name: self.edit_mapping(sn))
self.table.setCellWidget(row, 2, edit_btn)
# Delete button
delete_btn = QPushButton("🗑️ Delete")
delete_btn.setStyleSheet("""
QPushButton {
background-color: #f44336;
color: white;
padding: 4px 10px;
border-radius: 3px;
}
QPushButton:hover {
background-color: #d32f2f;
}
""")
delete_btn.clicked.connect(lambda checked, sn=short_name: self.delete_mapping(sn))
self.table.setCellWidget(row, 3, delete_btn)
self.count_label.setText(f"Total Students: {len(self.mappings)}")
def import_from_csv(self):
"""Import student mappings from CSV file"""
file_path, _ = QFileDialog.getOpenFileName(
self,
"Select Student Names CSV",
str(Path.home()),
"CSV Files (*.csv *.CSV);;All Files (*)"
)
if not file_path:
return
try:
import csv
added_count = 0
updated_count = 0
with open(file_path, 'r', encoding='utf-8') as f:
csv_reader = csv.reader(f)
# Skip header if present
first_row = next(csv_reader, None)
if first_row and ('short' in first_row[0].lower() or 'name' in first_row[0].lower()):
# Header row, skip it
pass
else:
# Not a header, process it
if first_row and len(first_row) >= 2:
short_name = first_row[0].strip()
full_name = first_row[1].strip()
if short_name and full_name:
if short_name in self.mappings:
updated_count += 1
else:
added_count += 1
self.mappings[short_name] = full_name
# Process remaining rows
for row in csv_reader:
if len(row) >= 2:
short_name = row[0].strip()
full_name = row[1].strip()
if short_name and full_name:
if short_name in self.mappings:
updated_count += 1
else:
added_count += 1
self.mappings[short_name] = full_name
self.update_table()
QMessageBox.information(
self,
"Import Successful",
f"Imported student names:\n\n"
f"• Added: {added_count} new students\n"
f"• Updated: {updated_count} existing students\n"
f"• Total: {len(self.mappings)} students"
)
except Exception as e:
QMessageBox.critical(self, "Import Error", f"Failed to import CSV:\n{str(e)}")
def import_from_excel(self):
"""Import student mappings from Excel file"""
file_path, _ = QFileDialog.getOpenFileName(
self,
"Select Student Names Excel File",
str(Path.home()),
"Excel Files (*.xlsx *.xls);;All Files (*)"
)
if not file_path:
return
try:
from openpyxl import load_workbook
added_count = 0
updated_count = 0
wb = load_workbook(file_path, data_only=True)
sheet = wb.active
for row_idx, row in enumerate(sheet.iter_rows(min_row=1, values_only=True), start=1):
# Skip header row
if row_idx == 1 and row[0] and ('short' in str(row[0]).lower() or 'name' in str(row[0]).lower()):
continue
if row and len(row) >= 2 and row[0] and row[1]:
short_name = str(row[0]).strip()
full_name = str(row[1]).strip()
if short_name and full_name:
if short_name in self.mappings:
updated_count += 1
else:
added_count += 1
self.mappings[short_name] = full_name
wb.close()
self.update_table()
QMessageBox.information(
self,
"Import Successful",
f"Imported student names:\n\n"
f"• Added: {added_count} new students\n"
f"• Updated: {updated_count} existing students\n"
f"• Total: {len(self.mappings)} students"
)
except Exception as e:
QMessageBox.critical(self, "Import Error", f"Failed to import Excel:\n{str(e)}")
def export_to_excel(self):
"""Export current student mappings to Excel"""
file_path, _ = QFileDialog.getSaveFileName(
self,
"Export Student Names",
str(Path.home() / f"student_names_{datetime.now().strftime('%Y%m%d_%H%M%S')}.xlsx"),
"Excel Files (*.xlsx);;All Files (*)"
)
if not file_path:
return
try:
from openpyxl import Workbook
from openpyxl.styles import Font, PatternFill, Alignment
wb = Workbook()
ws = wb.active
ws.title = "Student Names"
# Headers
ws['A1'] = "Short Name"
ws['B1'] = "Full Student Name"
for cell in ['A1', 'B1']:
ws[cell].font = Font(bold=True, color="FFFFFF")
ws[cell].fill = PatternFill(start_color="4472C4", end_color="4472C4", fill_type="solid")
ws[cell].alignment = Alignment(horizontal="center", vertical="center")
# Data
for row_idx, (short_name, full_name) in enumerate(sorted(self.mappings.items()), start=2):
ws[f'A{row_idx}'] = short_name
ws[f'B{row_idx}'] = full_name
# Column widths
ws.column_dimensions['A'].width = 20
ws.column_dimensions['B'].width = 35
wb.save(file_path)
QMessageBox.information(
self,
"Export Successful",
f"Exported {len(self.mappings)} student names to:\n{Path(file_path).name}"
)
except Exception as e:
QMessageBox.critical(self, "Export Error", f"Failed to export Excel:\n{str(e)}")
def delete_mapping(self, short_name):
"""Delete a student mapping"""
reply = QMessageBox.question(
self,
"Confirm Delete",
f"Delete student mapping?\n\nShort Name: {short_name}\nFull Name: {self.mappings[short_name]}",
QMessageBox.Yes | QMessageBox.No,
QMessageBox.No
)
if reply == QMessageBox.Yes:
del self.mappings[short_name]
self.update_table()
def edit_mapping(self, short_name):
"""Edit a student mapping"""
from PySide6.QtWidgets import QDialog, QVBoxLayout, QFormLayout, QLineEdit, QDialogButtonBox
dialog = QDialog(self)
dialog.setWindowTitle("Edit Student Mapping")
dialog.setMinimumWidth(400)
layout = QVBoxLayout(dialog)
form_layout = QFormLayout()
# Short name input
short_name_input = QLineEdit(short_name)
short_name_input.setStyleSheet("padding: 8px; border: 2px solid #ccc; border-radius: 5px;")
form_layout.addRow("Short Name:", short_name_input)
# Full name input
full_name_input = QLineEdit(self.mappings[short_name])
full_name_input.setStyleSheet("padding: 8px; border: 2px solid #ccc; border-radius: 5px;")
form_layout.addRow("Full Student Name:", full_name_input)
layout.addLayout(form_layout)
# Dialog buttons
button_box = QDialogButtonBox(QDialogButtonBox.Save | QDialogButtonBox.Cancel)
button_box.accepted.connect(dialog.accept)
button_box.rejected.connect(dialog.reject)
layout.addWidget(button_box)
if dialog.exec() == QDialog.Accepted: