-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtask_assignment_tool.py
More file actions
2307 lines (1949 loc) · 96.1 KB
/
task_assignment_tool.py
File metadata and controls
2307 lines (1949 loc) · 96.1 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
import streamlit as st
import pandas as pd
import numpy as np
from datetime import datetime, timedelta
import json
from collections import Counter, defaultdict
import statistics
import requests
from typing import Dict, List, Any
import os
import time
import io
import re
import hashlib
# Page config
st.set_page_config(
page_title="Team Task Assignment Tool",
page_icon="📋",
layout="wide"
)
# GitHub Configuration
GITHUB_TOKEN = st.secrets.get("github", {}).get("token", "")
GITHUB_REPO = st.secrets.get("github", {}).get("repo", "")
GITHUB_BRANCH = st.secrets.get("github", {}).get("branch", "main")
# User Authentication Configuration
USERS_FILE = "users_auth.json"
# Initialize session state
if 'authenticated' not in st.session_state:
st.session_state.authenticated = False
if 'current_username' not in st.session_state:
st.session_state.current_username = None
if 'current_user' not in st.session_state:
st.session_state.current_user = None
if 'roster_data' not in st.session_state:
st.session_state.roster_data = None
if 'show_conflict_message' not in st.session_state:
st.session_state.show_conflict_message = False
if 'last_conflict_message' not in st.session_state:
st.session_state.last_conflict_message = None
if 'show_reset_confirmation' not in st.session_state:
st.session_state.show_reset_confirmation = False
if 'last_uploaded_file_id' not in st.session_state:
st.session_state.last_uploaded_file_id = None
if 'file_upload_count' not in st.session_state:
st.session_state.file_upload_count = 0
if 'last_roster_count' not in st.session_state:
st.session_state.last_roster_count = 0
if 'recovery_mode' not in st.session_state:
st.session_state.recovery_mode = False
if 'recovery_user' not in st.session_state:
st.session_state.recovery_user = None
# Authentication Functions
def hash_password(password):
"""Hash a password for storing"""
return hashlib.sha256(password.encode()).hexdigest()
def get_users():
"""Load users from GitHub"""
if not GITHUB_TOKEN or not GITHUB_REPO:
return {}
try:
url = f"https://api.github.com/repos/{GITHUB_REPO}/contents/{USERS_FILE}?ref={GITHUB_BRANCH}"
headers = {"Authorization": f"token {GITHUB_TOKEN}", "Accept": "application/vnd.github.v3+json"}
response = requests.get(url, headers=headers)
if response.status_code == 200:
content = response.json()
import base64
users = json.loads(base64.b64decode(content['content']).decode('utf-8'))
return users
elif response.status_code == 404:
# No users file yet
return {}
except:
return {}
return {}
def save_users(users_dict):
"""Save users to GitHub"""
try:
import base64
content = base64.b64encode(json.dumps(users_dict, indent=2).encode('utf-8')).decode('utf-8')
# Check if file exists to get SHA
url = f"https://api.github.com/repos/{GITHUB_REPO}/contents/{USERS_FILE}?ref={GITHUB_BRANCH}"
headers = {"Authorization": f"token {GITHUB_TOKEN}", "Accept": "application/vnd.github.v3+json"}
response = requests.get(url, headers=headers)
sha = None
if response.status_code == 200:
sha = response.json()['sha']
# Save file
payload = {
"message": f"Update users - {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}",
"content": content,
"branch": GITHUB_BRANCH
}
if sha:
payload["sha"] = sha
response = requests.put(url, json=payload, headers=headers)
return response.status_code in [200, 201]
except:
return False
def register_user(username, password, display_name, security_question, security_answer):
"""Register a new user with security question"""
users = get_users()
if username in users:
return False, "Username already exists"
users[username] = {
"password": hash_password(password),
"display_name": display_name,
"security_question": security_question,
"security_answer": hash_password(security_answer.lower().strip()), # Hash the answer too
"created_at": datetime.now().isoformat(),
"data_file": f"user_{username}_data.json"
}
if save_users(users):
return True, "Registration successful"
return False, "Failed to save user"
def authenticate_user(username, password):
"""Authenticate a user"""
users = get_users()
if username not in users:
return False, "User not found"
if users[username]["password"] == hash_password(password):
return True, users[username]
return False, "Invalid password"
def verify_security_answer(username, answer):
"""Verify security answer"""
users = get_users()
if username not in users:
return False
stored_answer = users[username].get("security_answer", "")
return stored_answer == hash_password(answer.lower().strip())
def reset_password(username, new_password):
"""Reset user password"""
users = get_users()
if username not in users:
return False
users[username]['password'] = hash_password(new_password)
return save_users(users)
def get_user_data_file():
"""Get the data file for current user"""
if st.session_state.current_username:
return f"user_{st.session_state.current_username}_data.json"
return None
# GitHub API Functions
def get_github_headers():
"""Get headers for GitHub API requests"""
return {
"Authorization": f"token {GITHUB_TOKEN}",
"Accept": "application/vnd.github.v3+json"
}
def get_data_from_github():
"""Load data from GitHub for current user"""
if not GITHUB_TOKEN or not GITHUB_REPO:
return None, None
data_file = get_user_data_file()
if not data_file:
return None, None
try:
url = f"https://api.github.com/repos/{GITHUB_REPO}/contents/{data_file}?ref={GITHUB_BRANCH}"
response = requests.get(url, headers=get_github_headers())
if response.status_code == 200:
content = response.json()
import base64
data = json.loads(base64.b64decode(content['content']).decode('utf-8'))
return data, content['sha']
elif response.status_code == 404:
# File doesn't exist yet, return empty structure
return {
"username": st.session_state.current_username,
"tasks": {},
"assignments": {},
"completed_tasks": [],
"task_counter": 1,
"assignment_history": [],
"last_modified": {
"user": st.session_state.current_user,
"timestamp": datetime.now().isoformat()
}
}, None
else:
st.error(f"GitHub API error: {response.status_code}")
return None, None
except Exception as e:
st.error(f"Error loading data from GitHub: {e}")
return None, None
def save_data_to_github(data, sha=None, retry_count=0):
"""Save data to GitHub for current user"""
if not GITHUB_TOKEN or not GITHUB_REPO:
st.error("GitHub configuration missing in secrets")
return False
data_file = get_user_data_file()
if not data_file:
return False
if retry_count > 3:
st.error("Failed to save after multiple attempts. Please refresh and try again.")
return False
try:
# Add username and last modified info
data["username"] = st.session_state.current_username
data["last_modified"] = {
"user": st.session_state.current_user,
"timestamp": datetime.now().isoformat()
}
import base64
content = base64.b64encode(json.dumps(data, indent=2).encode('utf-8')).decode('utf-8')
url = f"https://api.github.com/repos/{GITHUB_REPO}/contents/{data_file}"
payload = {
"message": f"Update by {st.session_state.current_user} - {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}",
"content": content,
"branch": GITHUB_BRANCH
}
if sha:
payload["sha"] = sha
response = requests.put(url, json=payload, headers=get_github_headers())
if response.status_code in [200, 201]:
return True
elif response.status_code == 409:
# Conflict - someone else updated the file
if retry_count == 0:
st.warning("⚠️ Another user updated the data. Attempting to merge changes...")
# Get the latest data
latest_data, latest_sha = get_data_from_github()
if latest_data:
# Merge the changes
if "tasks" in data and "tasks" in latest_data:
latest_data["tasks"].update(data["tasks"])
if "assignments" in data and "assignments" in latest_data:
latest_data["assignments"].update(data["assignments"])
if "completed_tasks" in data:
existing_ids = {ct['task_id'] for ct in latest_data.get("completed_tasks", [])}
for ct in data.get("completed_tasks", []):
if ct['task_id'] not in existing_ids:
latest_data["completed_tasks"].append(ct)
if "assignment_history" in data:
latest_data["assignment_history"].extend(data.get("assignment_history", []))
if "task_counter" in data:
latest_data["task_counter"] = max(data.get("task_counter", 1), latest_data.get("task_counter", 1))
# Retry with merged data
time.sleep(0.5)
return save_data_to_github(latest_data, latest_sha, retry_count + 1)
else:
st.error("Failed to resolve conflict. Please refresh the page.")
return False
else:
st.error(f"GitHub save error: {response.status_code}")
return False
except Exception as e:
st.error(f"Error saving to GitHub: {e}")
return False
# Data Management Functions
@st.cache_data(ttl=5)
def load_all_data():
"""Load all data from GitHub"""
data, sha = get_data_from_github()
if data:
# Ensure all fields exist
if "assignment_history" not in data:
data["assignment_history"] = []
if "last_modified" not in data:
data["last_modified"] = {
"user": "Unknown",
"timestamp": datetime.now().isoformat()
}
return data, sha
return {
"username": st.session_state.current_username,
"tasks": {},
"assignments": {},
"completed_tasks": [],
"task_counter": 1,
"assignment_history": [],
"last_modified": {
"user": "System",
"timestamp": datetime.now().isoformat()
}
}, None
def save_all_data(data):
"""Save all data to GitHub"""
_, current_sha = get_data_from_github()
success = save_data_to_github(data, current_sha)
if success:
st.cache_data.clear()
return success
def reset_all_data():
"""Reset all data to start fresh"""
data = {
"username": st.session_state.current_username,
"tasks": {},
"assignments": {},
"completed_tasks": [],
"task_counter": 1,
"assignment_history": [],
"last_modified": {
"user": st.session_state.current_user,
"timestamp": datetime.now().isoformat()
}
}
return save_all_data(data)
def load_tasks():
"""Load tasks from storage"""
data, _ = load_all_data()
return data.get("tasks", {})
def save_task(task_id, task_info):
"""Save a task"""
max_retries = 3
for attempt in range(max_retries):
data, _ = load_all_data()
if "tasks" not in data:
data["tasks"] = {}
data["tasks"][task_id] = task_info
if save_all_data(data):
return True
if attempt < max_retries - 1:
st.warning(f"Retrying save... (Attempt {attempt + 2}/{max_retries})")
time.sleep(1)
return False
def delete_task(task_id):
"""Delete a task"""
data, _ = load_all_data()
if task_id in data.get("tasks", {}):
del data["tasks"][task_id]
if task_id in data.get("assignments", {}):
del data["assignments"][task_id]
save_all_data(data)
def load_assignments():
"""Load assignments"""
data, _ = load_all_data()
return data.get("assignments", {})
def save_assignments(task_id, testers):
"""Save assignments and track history"""
max_retries = 3
for attempt in range(max_retries):
data, _ = load_all_data()
if "assignments" not in data:
data["assignments"] = {}
# Track assignment history
task_info = data.get("tasks", {}).get(task_id, {})
if "assignment_history" not in data:
data["assignment_history"] = []
for tester in testers:
data["assignment_history"].append({
"task_id": task_id,
"task_name": task_info.get("name", "Unknown"),
"tester": tester,
"assigned_at": datetime.now().isoformat(),
"assigned_by": st.session_state.current_user,
"languages": task_info.get("languages", []),
"priority": task_info.get("priority", "Unknown")
})
data["assignments"][task_id] = testers
if save_all_data(data):
return True
if attempt < max_retries - 1:
st.warning(f"Retrying save... (Attempt {attempt + 2}/{max_retries})")
time.sleep(1)
return False
def load_completed_tasks():
"""Load completed tasks"""
data, _ = load_all_data()
return data.get("completed_tasks", [])
def mark_task_completed(task_id, completed_by):
"""Mark a task as completed"""
data, _ = load_all_data()
task_info = data.get("tasks", {}).get(task_id, {})
assignees = data.get("assignments", {}).get(task_id, [])
if "completed_tasks" not in data:
data["completed_tasks"] = []
data["completed_tasks"].append({
'task_id': task_id,
'task_name': task_info.get('name', 'Unknown'),
'completed_by': completed_by,
'completed_at': datetime.now().isoformat(),
'assignees': assignees,
'languages': task_info.get('languages', []),
'priority': task_info.get('priority', 'Unknown'),
'created_by': task_info.get('created_by', 'Unknown'),
'created_at': task_info.get('created_at', '')
})
save_all_data(data)
def get_task_counter():
"""Get the next task counter"""
data, _ = load_all_data()
counter = data.get("task_counter", 1)
data["task_counter"] = counter + 1
save_all_data(data)
return counter
def load_assignment_history():
"""Load assignment history"""
data, _ = load_all_data()
return data.get("assignment_history", [])
def get_last_modified_info():
"""Get information about last modification"""
data, _ = load_all_data()
last_modified = data.get("last_modified", {})
return last_modified.get("user", "Unknown"), last_modified.get("timestamp", "Unknown")
# Helper Functions
def make_columns_unique(columns):
"""Make duplicate column names unique by adding suffixes"""
seen = {}
unique_columns = []
for col in columns:
col_str = str(col).strip()
if col_str in seen:
seen[col_str] += 1
unique_columns.append(f"{col_str}_{seen[col_str]}")
else:
seen[col_str] = 1
unique_columns.append(col_str)
return unique_columns
def parse_csv_ultra_smart(file_content):
"""Ultra-smart CSV parser that handles various edge cases"""
try:
file_content.seek(0)
raw_content = file_content.read()
file_content.seek(0)
# Try to decode with different encodings
text_content = None
for encoding in ['utf-8', 'latin-1', 'cp1252', 'iso-8859-1']:
try:
if isinstance(raw_content, bytes):
text_content = raw_content.decode(encoding)
else:
text_content = raw_content
break
except:
continue
if not text_content:
raise ValueError("Could not decode file with any encoding")
lines = text_content.strip().split('\n')
if not lines:
raise ValueError("Empty file")
def looks_like_headers(values):
"""Check if values look like column headers"""
if not values:
return False
header_patterns = [
'first', 'last', 'name', 'language', 'lang', 'device',
'serial', 'type', 'index', 'experience', 'currently', 'used'
]
values_lower = [str(v).lower() for v in values if v]
matches = sum(1 for v in values_lower for pattern in header_patterns if pattern in v)
return matches >= 2
def parse_csv_line(line, delimiter=','):
"""Parse a CSV line handling quotes properly"""
values = []
current_value = ""
in_quotes = False
for i, char in enumerate(line):
if char == '"' and (i == 0 or line[i-1] != '\\'):
in_quotes = not in_quotes
elif char == delimiter and not in_quotes:
values.append(current_value.strip().strip('"'))
current_value = ""
else:
current_value += char
if current_value:
values.append(current_value.strip().strip('"'))
return values
# Try different delimiters
best_delimiter = ','
max_columns = 0
for delimiter in [',', '\t', ';', '|']:
first_line_values = parse_csv_line(lines[0], delimiter)
if len(first_line_values) > max_columns:
max_columns = len(first_line_values)
best_delimiter = delimiter
# Parse all lines with best delimiter
all_data = []
for line in lines:
if line.strip():
values = parse_csv_line(line, best_delimiter)
all_data.append(values)
if not all_data:
raise ValueError("No data found")
# Find the header row
header_row_idx = 0
for i in range(min(3, len(all_data))):
if looks_like_headers(all_data[i]):
header_row_idx = i
break
# Special case: if first row is just letters (A, B, C...) skip it
first_row = all_data[0]
if all(len(str(v).strip()) <= 2 and str(v).strip().isalpha() for v in first_row if v):
header_row_idx = 1
headers = all_data[header_row_idx] if header_row_idx < len(all_data) else all_data[0]
data_rows = all_data[header_row_idx + 1:] if header_row_idx + 1 < len(all_data) else []
headers = [str(h).strip() for h in headers]
headers = make_columns_unique(headers)
max_cols = len(headers)
cleaned_data = []
for row in data_rows:
while len(row) < max_cols:
row.append('')
row = row[:max_cols]
cleaned_data.append(row)
df = pd.DataFrame(cleaned_data, columns=headers)
df = df.dropna(how='all')
df = df[~(df == '').all(axis=1)]
return df
except Exception as e:
try:
file_content.seek(0)
df = pd.read_csv(file_content)
if df.columns.duplicated().any():
df.columns = make_columns_unique(df.columns.tolist())
return df
except Exception as pandas_error:
raise Exception(f"Failed to parse CSV: {str(e)}. Pandas error: {str(pandas_error)}")
def normalize_column_names(df):
"""Normalize column names with extensive mapping"""
if df.empty:
return df
# Remove any unnamed columns at the start
while len(df.columns) > 0 and (
'unnamed' in str(df.columns[0]).lower() or
df.columns[0] == '' or
pd.isna(df.columns[0]) or
(isinstance(df.columns[0], str) and df.columns[0].isdigit())
):
df = df.iloc[:, 1:]
# Create comprehensive mapping
column_mappings = {
'first_name': [
'first_name', 'firstname', 'first name', 'fname', 'given_name',
'given name', 'first', 'name', 'forename', 'prenom', 'given'
],
'last_name': [
'last_name', 'lastname', 'last name', 'lname', 'surname',
'family_name', 'family name', 'last', 'family', 'nom'
],
'language_1': [
'language_1', 'language1', 'language 1', 'lang1', 'lang_1',
'lang 1', 'primary_language', 'primary language', 'language',
'first_language', 'first language'
],
'language_2': [
'language_2', 'language2', 'language 2', 'lang2', 'lang_2',
'lang 2', 'secondary_language', 'secondary language',
'second_language', 'second language'
],
'language_3': [
'language_3', 'language3', 'language 3', 'lang3', 'lang_3',
'lang 3', 'third_language', 'third language'
],
'language_4': [
'language_4', 'language4', 'language 4', 'lang4', 'lang_4',
'lang 4', 'fourth_language', 'fourth language'
],
'public_device_name': [
'public_device_name', 'device_name', 'device name', 'device',
'public device name', 'device_id', 'device id'
],
'public_device_name_2': [
'public_device_name_2', 'public_device_name_2', 'device_name_2',
'device name 2', 'device 2', 'public device name 2'
],
'public_device_name_3': [
'public_device_name_3', 'public_device_name_3', 'device_name_3',
'device name 3', 'device 3', 'public device name 3'
],
'public_device_name_4': [
'public_device_name_4', 'public_device_name_4', 'device_name_4',
'device name 4', 'device 4', 'public device name 4'
],
'device_type': [
'device_type', 'type', 'device type', 'device_model', 'model'
],
'device_type_2': [
'device_type_2', 'type_2', 'device type 2', 'device_model_2', 'model 2'
],
'device_type_3': [
'device_type_3', 'type_3', 'device type 3', 'device_model_3', 'model 3'
],
'device_type_4': [
'device_type_4', 'type_4', 'device type 4', 'device_model_4', 'model 4'
],
'serial_number': [
'serial_number', 'serial', 'sn', 'serial number', 'serial no',
'serial_no', 'serialnumber', 'serial#'
],
'serial_number_2': [
'serial_number_2', 'serial_2', 'sn_2', 'serial number 2', 'serial no 2'
],
'serial_number_3': [
'serial_number_3', 'serial_3', 'sn_3', 'serial number 3', 'serial no 3'
],
'serial_number_4': [
'serial_number_4', 'serial_4', 'sn_4', 'serial number 4', 'serial no 4'
],
'currently_used_by': [
'currently_used_by', 'used_by', 'current_user', 'used by',
'currently used by', 'current user', 'assigned_to', 'assigned to'
],
'currently_used_by_2': [
'currently_used_by_2', 'currently used by_2', 'used_by_2', 'used by 2'
],
'currently_used_by_3': [
'currently_used_by_3', 'currently used by_3', 'used_by_3', 'used by 3'
],
'currently_used_by_4': [
'currently_used_by_4', 'currently used by_4', 'used_by_4', 'used by 4'
]
}
# Apply mapping
new_columns = {}
used_mappings = set()
for col in df.columns:
if pd.isna(col) or str(col).strip() == '':
continue
col_lower = str(col).strip().lower()
mapped = False
# Try exact match first
for standard_name, variations in column_mappings.items():
if col_lower in variations:
new_columns[col] = standard_name
used_mappings.add(standard_name)
mapped = True
break
# If no exact match, try partial match
if not mapped:
for standard_name, variations in column_mappings.items():
if standard_name not in used_mappings:
for variation in variations:
if variation in col_lower or col_lower in variation:
new_columns[col] = standard_name
used_mappings.add(standard_name)
mapped = True
break
if mapped:
break
# If still no match, clean the column name
if not mapped:
clean_name = re.sub(r'[^a-zA-Z0-9_]', '_', col_lower)
clean_name = re.sub(r'_+', '_', clean_name).strip('_')
new_columns[col] = clean_name if clean_name else f'column_{len(new_columns)}'
df = df.rename(columns=new_columns)
df = df.dropna(axis=1, how='all')
return df
def validate_required_columns(df):
"""Check required columns"""
required = ['first_name', 'last_name']
missing = []
for col in required:
if col not in df.columns:
missing.append(col)
return missing
def normalize_language(lang):
"""Normalize language codes"""
if pd.isna(lang) or lang == '' or str(lang).lower() == 'nan':
return None
lang = str(lang).strip()
lang_upper = lang.upper()
# Skip NA (Not Applicable)
if lang_upper == 'NA' or lang_upper == 'N/A':
return None
language_map = {
'EN': 'English', 'EN_US': 'English', 'EN_GB': 'English', 'EN_IE': 'English',
'EN_AU': 'English', 'EN_CA': 'English', 'ENGLISH': 'English',
'IT': 'Italian', 'IT_IT': 'Italian', 'ITALIAN': 'Italian',
'FR': 'French', 'FR_FR': 'French', 'FR_CA': 'French', 'FRENCH': 'French',
'NB': 'Norwegian', 'NB_NO': 'Norwegian', 'NO': 'Norwegian', 'NORWEGIAN': 'Norwegian',
'RU': 'Russian', 'RU_RU': 'Russian', 'RUSSIAN': 'Russian',
'ZH': 'Chinese', 'ZH_CN': 'Chinese (Simplified)', 'ZH_XC': 'Chinese (Simplified)',
'ZH_TW': 'Chinese (Traditional)', 'CHINESE': 'Chinese',
'HE': 'Hebrew', 'HE_IL': 'Hebrew', 'IL_HE': 'Hebrew', 'HEBREW': 'Hebrew',
'DE': 'German', 'DE_DE': 'German', 'GERMAN': 'German',
'ES': 'Spanish', 'ES_ES': 'Spanish', 'ES_MX': 'Spanish', 'SPANISH': 'Spanish',
'PT': 'Portuguese', 'PT_PT': 'Portuguese', 'PT_BR': 'Portuguese', 'PORTUGUESE': 'Portuguese',
'JA': 'Japanese', 'JA_JP': 'Japanese', 'JAPANESE': 'Japanese',
'KO': 'Korean', 'KO_KR': 'Korean', 'KOREAN': 'Korean',
'NL': 'Dutch', 'NL_NL': 'Dutch', 'DUTCH': 'Dutch',
'SV': 'Swedish', 'SV_SE': 'Swedish', 'SWEDISH': 'Swedish',
'DA': 'Danish', 'DA_DK': 'Danish', 'DANISH': 'Danish',
'FI': 'Finnish', 'FI_FI': 'Finnish', 'FINNISH': 'Finnish',
'PL': 'Polish', 'PL_PL': 'Polish', 'POLISH': 'Polish',
'TR': 'Turkish', 'TR_TR': 'Turkish', 'TURKISH': 'Turkish',
'AR': 'Arabic', 'AR_SA': 'Arabic', 'ARABIC': 'Arabic',
'TH': 'Thai', 'TH_TH': 'Thai', 'THAI': 'Thai',
'HI': 'Hindi', 'HI_IN': 'Hindi', 'HINDI': 'Hindi',
}
if '_' in lang.lower():
prefix = lang.lower().split('_')[0].upper()
if prefix in language_map:
return language_map[prefix]
if lang_upper in language_map:
return language_map[lang_upper]
return lang.capitalize()
def validate_roster_data(df):
"""Validate roster data"""
issues = []
if 'first_name' in df.columns and 'last_name' in df.columns:
df['first_name'] = df['first_name'].fillna('')
df['last_name'] = df['last_name'].fillna('')
df['full_name'] = df['first_name'].astype(str) + ' ' + df['last_name'].astype(str)
valid_names = df[df['full_name'].str.strip() != '']
if not valid_names.empty:
duplicates = valid_names[valid_names.duplicated(subset=['full_name'], keep=False)]
if not duplicates.empty:
duplicate_names = duplicates['full_name'].unique().tolist()
issues.append(f"⚠️ Duplicates: {', '.join(duplicate_names)}")
return issues
def get_tester_languages(row):
"""Get languages for a tester"""
languages = set()
for col in ['language_1', 'language_2', 'language_3', 'language_4']:
if col in row.index:
lang = normalize_language(row[col])
if lang:
languages.add(lang)
return languages
def get_tester_device_info(row):
"""Get device information for a tester"""
device_info = {}
# Check for primary device
if 'public_device_name' in row.index and pd.notna(row['public_device_name']):
device_info['device_name'] = str(row['public_device_name'])
if 'device_type' in row.index and pd.notna(row['device_type']):
device_info['device_type'] = str(row['device_type'])
if 'serial_number' in row.index and pd.notna(row['serial_number']):
device_info['serial_number'] = str(row['serial_number'])
if 'currently_used_by' in row.index and pd.notna(row['currently_used_by']):
device_info['currently_used_by'] = str(row['currently_used_by'])
# Check for additional devices (2, 3, 4)
for i in range(2, 5):
device_key = f'device_{i}'
if f'public_device_name_{i}' in row.index and pd.notna(row[f'public_device_name_{i}']):
if device_key not in device_info:
device_info[device_key] = {}
device_info[device_key]['device_name'] = str(row[f'public_device_name_{i}'])
if f'device_type_{i}' in row.index and pd.notna(row[f'device_type_{i}']):
if device_key not in device_info:
device_info[device_key] = {}
device_info[device_key]['device_type'] = str(row[f'device_type_{i}'])
if f'serial_number_{i}' in row.index and pd.notna(row[f'serial_number_{i}']):
if device_key not in device_info:
device_info[device_key] = {}
device_info[device_key]['serial_number'] = str(row[f'serial_number_{i}'])
if f'currently_used_by_{i}' in row.index and pd.notna(row[f'currently_used_by_{i}']):
if device_key not in device_info:
device_info[device_key] = {}
device_info[device_key]['currently_used_by'] = str(row[f'currently_used_by_{i}'])
return device_info
def get_available_testers(language_requirements, match_all=False):
"""Get available testers"""
if st.session_state.roster_data is None:
return []
tasks = load_tasks()
assignments = load_assignments()
completed_tasks = load_completed_tasks()
completed_task_ids = [ct['task_id'] for ct in completed_tasks]
available_testers = []
df = st.session_state.roster_data.fillna('')
for _, row in df.iterrows():
if not row.get('first_name') or not row.get('last_name'):
continue
full_name = f"{row['first_name']} {row['last_name']}".strip()
if not full_name or full_name == ' ':
continue
tester_languages = get_tester_languages(row)
device_info = get_tester_device_info(row)
if match_all:
language_match = all(lang in tester_languages for lang in language_requirements)
else:
language_match = any(lang in tester_languages for lang in language_requirements) if language_requirements else True
if language_match or not language_requirements:
assigned_task_names = {}
for task_id, task_info in tasks.items():
if task_id not in completed_task_ids:
if full_name in assignments.get(task_id, []):
assigned_task_names[task_info['name']] = task_info['priority']
assigned_tasks = [(name, priority) for name, priority in assigned_task_names.items()]
matching_languages = [lang for lang in language_requirements if lang in tester_languages]
available_testers.append({
'name': full_name,
'languages': tester_languages,
'matching_languages': matching_languages,
'assigned_tasks': assigned_tasks,
'is_available': len(assigned_tasks) == 0,
'device_info': device_info
})
available_testers.sort(key=lambda x: (-len(x['matching_languages']), not x['is_available'], x['name']))
return available_testers
def get_all_testers_with_languages():
"""Get all testers with their language information"""
if st.session_state.roster_data is None:
return []
testers = []
df = st.session_state.roster_data.fillna('')
for _, row in df.iterrows():
if not row.get('first_name') or not row.get('last_name'):
continue
full_name = f"{row['first_name']} {row['last_name']}".strip()
if not full_name or full_name == ' ':
continue
tester_languages = get_tester_languages(row)
testers.append({
'name': full_name,
'languages': tester_languages
})
return testers
def get_multi_assigned_testers():
"""Get list of testers assigned to multiple active tasks"""
tasks = load_tasks()
assignments = load_assignments()
completed_tasks = load_completed_tasks()
completed_task_ids = [ct['task_id'] for ct in completed_tasks]
tester_assignments = defaultdict(list)
for task_id, assignees in assignments.items():
if task_id not in completed_task_ids:
task_info = tasks.get(task_id, {})
for tester in assignees:
tester_assignments[tester].append({
'task_id': task_id,
'task_name': task_info.get('name', 'Unknown'),
'priority': task_info.get('priority', 'Unknown'),
'languages': task_info.get('languages', [])
})
multi_assigned = {}
for tester, tasks_list in tester_assignments.items():
if len(tasks_list) > 1:
multi_assigned[tester] = tasks_list
return multi_assigned
def generate_detailed_report():
"""Generate comprehensive analytics report"""
tasks = load_tasks()
assignments = load_assignments()
completed_tasks = load_completed_tasks()
assignment_history = load_assignment_history()
completed_task_ids = [ct['task_id'] for ct in completed_tasks]
total_tasks = len(tasks)
active_tasks = [(tid, tinfo) for tid, tinfo in tasks.items() if tid not in completed_task_ids]
now = datetime.now()
week_ago = now - timedelta(days=7)
month_ago = now - timedelta(days=30)
total_testers = len(st.session_state.roster_data) if st.session_state.roster_data is not None else 0
# Active assignments
assigned_testers = set()
tester_workload = defaultdict(int)
for task_id, assignees in assignments.items():
if task_id not in completed_task_ids: