-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexcel_search_gui.py
More file actions
1870 lines (1544 loc) · 78.4 KB
/
excel_search_gui.py
File metadata and controls
1870 lines (1544 loc) · 78.4 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
# edrl_excel_search_gui_v6.py
#
# FULL FILE (Search + Results + Request Queue + Request Form + Attachments)
#
# v6 updates:
# - Adds Queue Search (global across all queue columns)
# - Adds "Emergency Only" toggle on Queue tab
#
# Dependencies:
# pip install pandas openpyxl
#
# Run:
# python edrl_excel_search_gui_v6.py
import os
import sys
import re
import calendar
import json
import time
from PIL import Image, ImageTk
import tkinter as tk
from tkinter import ttk, filedialog, messagebox
import pandas as pd
from openpyxl import load_workbook
def resource_path(relative_path: str) -> str:
base_path = getattr(sys, "_MEIPASS", os.path.abspath("."))
return os.path.join(base_path, relative_path)
DEFAULT_WORKBOOK = resource_path(os.path.join("samples", "Example_Software_List.xlsx"))
def appdata_path(filename: str) -> str:
base = os.environ.get("LOCALAPPDATA") or os.environ.get("APPDATA") or os.path.abspath(".")
app_dir = os.path.join(base, "EDRL_Software_Search")
os.makedirs(app_dir, exist_ok=True)
return os.path.join(app_dir, filename)
# Persist Request Form window geometry between runs
REQ_FORM_GEOM_FILE = appdata_path("request_form_geometry.json")
BASE_FONT = ("Segoe UI", 12)
HEADER_FONT = ("Segoe UI", 18, "bold")
SUBHEADER_FONT = ("Segoe UI", 10)
BUTTON_FONT_BIG = ("Segoe UI", 14, "bold")
TREE_FONT = ("Segoe UI", 11)
TREE_HEADING_FONT = ("Segoe UI", 11, "bold")
BLUE_PRIMARY = "#1E5AA8"
LIGHT_BG = "#F3F8FF"
LIGHT_BG_2 = "#E6F0FF"
ROW_ODD = "#EAF2FF"
ROW_EVEN = "#FFFFFF"
NOISE_WORDS = {
"installer", "setup", "client", "enterprise", "x64", "64bit", "64-bit", "x86", "msi", "win32",
"machine", "wide", "machinewide", "update", "updater", "for", "windows", "mac", "osx", "macos",
"app", "application", "software", "tool", "tools"
}
def norm_text(s: str) -> str:
s = "" if s is None else str(s)
s = s.lower().strip()
s = re.sub(r"[^\w\s\.]", " ", s)
s = re.sub(r"\s+", " ", s).strip()
tokens = [t for t in s.split(" ") if t and t not in NOISE_WORDS]
return " ".join(tokens)
def extract_version_norm(v: str):
v = "" if v is None else str(v).lower()
cleaned = re.sub(r"[^0-9\.]", "", v)
parts = [p for p in cleaned.split(".") if p != ""]
nums = []
for p in parts[:6]:
try:
nums.append(int(p))
except Exception:
nums.append(0)
while len(nums) < 4:
nums.append(0)
return tuple(nums[:4])
def fmt_req_number(n: int) -> str:
return f"REQ-{n:04d}"
def normalize_state(value: str) -> str:
v = "" if value is None else str(value).strip().lower()
if v in {"approved", "approve", "yes", "y", "true", "1"}:
return "approved"
if v in {"not approved", "notapproved", "no", "n", "false", "0", "disapproved", "denied", "reject", "rejected"}:
return "not approved"
if "not" in v and "approved" in v:
return "not approved"
if "approved" in v:
return "approved"
return ""
def open_file_with_default_app(path: str):
if sys.platform.startswith("win"):
os.startfile(path) # type: ignore[attr-defined]
elif sys.platform.startswith("darwin"):
import subprocess
subprocess.run(["open", path], check=False)
else:
import subprocess
subprocess.run(["xdg-open", path], check=False)
def join_attachments(paths):
clean = []
for p in paths:
if not p:
continue
p = str(p).strip()
if p and p not in clean:
clean.append(p)
return " | ".join(clean)
def split_attachments(s: str):
s = "" if s is None else str(s)
parts = [p.strip() for p in s.split("|")]
return [p for p in parts if p]
class DatePicker(tk.Toplevel):
def __init__(self, parent, target_var: tk.StringVar, title="Select Date"):
super().__init__(parent)
self.title(title)
self.resizable(False, False)
self.transient(parent)
self.grab_set()
self.target_var = target_var
today = pd.Timestamp.now()
year = today.year
month = today.month
current = (target_var.get() or "").strip()
try:
if current:
dt = pd.to_datetime(current, errors="raise")
year = int(dt.year)
month = int(dt.month)
except Exception:
pass
self.year = tk.IntVar(value=year)
self.month = tk.IntVar(value=month)
top = ttk.Frame(self, padding=10)
top.pack(fill="x")
ttk.Label(top, text="Year").grid(row=0, column=0, sticky="w")
ttk.Spinbox(top, from_=2000, to=2100, textvariable=self.year, width=8, command=self.refresh).grid(
row=0, column=1, padx=(6, 14)
)
ttk.Label(top, text="Month").grid(row=0, column=2, sticky="w")
ttk.Spinbox(top, from_=1, to=12, textvariable=self.month, width=5, command=self.refresh).grid(
row=0, column=3, padx=(6, 0)
)
self.grid_frame = ttk.Frame(self, padding=(10, 0, 10, 10))
self.grid_frame.pack()
self.refresh()
def refresh(self):
for w in self.grid_frame.winfo_children():
w.destroy()
y = self.year.get()
m = self.month.get()
headers = ["Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"]
for i, h in enumerate(headers):
ttk.Label(self.grid_frame, text=h, width=4, anchor="center").grid(row=0, column=i)
cal = calendar.monthcalendar(y, m)
for r, week in enumerate(cal, start=1):
for c, day in enumerate(week):
if day == 0:
ttk.Label(self.grid_frame, text=" ", width=4).grid(row=r, column=c)
else:
ttk.Button(
self.grid_frame,
text=str(day),
width=4,
command=lambda d=day: self.select_date(y, m, d),
).grid(row=r, column=c, padx=1, pady=1)
def select_date(self, y, m, d):
self.target_var.set(f"{y:04d}-{m:02d}-{d:02d}")
self.destroy()
class ScrollableFrame(ttk.Frame):
"""A vertical scrollable container for forms so fields never get cut off."""
def __init__(self, parent, *args, **kwargs):
super().__init__(parent, *args, **kwargs)
# Prevent the form from becoming comically wide on large/zoomed windows.
# We'll cap the *content* width and center it inside the canvas.
self.max_inner_width = 1180
self.canvas = tk.Canvas(self, highlightthickness=0, bd=0)
self.vsb = ttk.Scrollbar(self, orient="vertical", command=self.canvas.yview)
self.canvas.configure(yscrollcommand=self.vsb.set)
self.inner = ttk.Frame(self.canvas)
self.inner_id = self.canvas.create_window((0, 0), window=self.inner, anchor="nw")
self.canvas.grid(row=0, column=0, sticky="nsew")
self.vsb.grid(row=0, column=1, sticky="ns")
self.rowconfigure(0, weight=1)
self.columnconfigure(0, weight=1)
self.inner.bind("<Configure>", self._on_inner_configure)
self.canvas.bind("<Configure>", self._on_canvas_configure)
# Mousewheel support (Windows/macOS/Linux)
self.canvas.bind_all("<MouseWheel>", self._on_mousewheel) # Windows/macOS
self.canvas.bind_all("<Button-4>", self._on_mousewheel_linux) # Linux up
self.canvas.bind_all("<Button-5>", self._on_mousewheel_linux) # Linux down
# Always start scrolled to the top after layout/scrollregion settles
self.after(30, lambda: self.canvas.yview_moveto(0.0))
self.after(150, lambda: self.canvas.yview_moveto(0.0)) # second tap for reliability
def _on_inner_configure(self, _):
self.canvas.configure(scrollregion=self.canvas.bbox("all"))
def _on_canvas_configure(self, event):
# Resize the inner frame to the usable canvas width (DPI-safe)
sbw = self.vsb.winfo_width()
if sbw <= 1:
sbw = 24 # fallback on first layout pass
try:
ht = int(self.canvas.cget("highlightthickness") or 0)
except Exception:
ht = 0
try:
bd = int(self.canvas.cget("bd") or 0)
except Exception:
bd = 0
usable = max(1, event.width - sbw - (ht * 2) - (bd * 2) - 12) # small safety gutter
w = min(usable, self.max_inner_width)
self.canvas.itemconfigure(self.inner_id, width=w)
self.canvas.coords(self.inner_id, 0, 0)
def _on_mousewheel(self, event):
if self.winfo_containing(event.x_root, event.y_root) is None:
return
# Windows delta is 120 increments
delta = -1 * int(event.delta / 120) if event.delta else 0
if delta:
self.canvas.yview_scroll(delta, "units")
def _on_mousewheel_linux(self, event):
if self.winfo_containing(event.x_root, event.y_root) is None:
return
if event.num == 4:
self.canvas.yview_scroll(-3, "units")
elif event.num == 5:
self.canvas.yview_scroll(3, "units")
class EDRLSearchGUI:
def __init__(self, root: tk.Tk):
self.root = root
self.root.title("Software Search")
self.root.geometry("1650x960")
self.root.minsize(1250, 760)
self.root.configure(bg=LIGHT_BG)
try:
self.root.option_add("*Font", f"{{{BASE_FONT[0]}}} {BASE_FONT[1]}")
except Exception:
pass
self.root.rowconfigure(0, weight=1)
self.root.columnconfigure(0, weight=1)
self.workbook_path = tk.StringVar(value=DEFAULT_WORKBOOK)
self.sheets = {}
self.idx_sheets = {}
self.current_sheet = tk.StringVar(value="All")
self.vendor_filter = tk.StringVar(value="(Any)")
self.platform_filter = tk.StringVar(value="(Any)")
self.status_filter = tk.StringVar(value="(Any)")
self.state_filter = tk.StringVar(value="(Any)")
self.search_field = tk.StringVar(value="All searchable fields")
self.query_var = tk.StringVar(value="")
self.name_query_var = tk.StringVar(value="")
self.dedup_var = tk.BooleanVar(value=True)
self.queue_query_var = tk.StringVar(value="")
self.queue_emergency_only_var = tk.BooleanVar(value=False)
self.platform_opts = ["Windows", "MacOS", "Cloud", "Mobile"]
self.auth_user_opts = [
"***OGC USE ONLY***",
"***Restricted***Approved Resonable Accommodation Only",
"***IT Cyber Use Only***",
"***IT USE ONLY***",
"DoDEA Staff",
"DoDEA Students",
"Medical",
"All",
]
self.type_opts = ["Cloud", "Software", "Extensions", "iOS", "Android"]
self.yesno_opts = ["Yes", "No"]
self.queue_columns_display = [
"EDRL Number",
"Name",
"Version",
"Type",
"Platform",
"Description",
"Instructional Need",
"Vendor",
"Authorization Date",
"Authorization Expiration",
"Date Added",
"State",
"Authorized User",
"Emergency",
"URL",
"Attachments",
"Software Assessments",
]
self._queue_internal_cols = ["_priority", "_created_ts"]
self.queue_df = pd.DataFrame(columns=self.queue_columns_display + self._queue_internal_cols)
self._apply_style()
# Load DoDEA logos (two sizes)
#self._dodea_logo_main = self._load_dodea_logo(max_height=500, cache_attr="_dodea_logo_main")
#self._dodea_logo_req = self._load_dodea_logo(max_height=175, cache_attr="_dodea_logo_req")
self._build_ui()
if os.path.exists(DEFAULT_WORKBOOK):
self.load_workbook(DEFAULT_WORKBOOK)
else:
self.status_var.set("Default workbook not found. Click Browse… to select your workbook.")
def _now_iso(self) -> str:
return pd.Timestamp.now().isoformat(timespec="seconds")
def _next_request_number(self) -> str:
if self.queue_df.empty or "EDRL Number" not in self.queue_df.columns:
return fmt_req_number(1)
max_n = 0
for v in self.queue_df["EDRL Number"].astype(str).tolist():
m = re.match(r"^REQ-(\d+)$", v.strip(), flags=re.IGNORECASE)
if m:
try:
max_n = max(max_n, int(m.group(1)))
except Exception:
pass
return fmt_req_number(max_n + 1)
# --- Request Form geometry persistence ---
# ---------------- Logo helper ----------------
def _load_dodea_logo(self, max_height: int, cache_attr: str = "_dodea_logo_img"):
"""Load DoDEA_Logo.png and resize to an exact max_height (pixel-accurate) using PIL. Cache on self."""
try:
path = resource_path("DoDEA_Logo.png")
if not os.path.exists(path):
setattr(self, cache_attr, None)
return None
img = Image.open(path).convert("RGBA")
w, h = img.size
if h <= 0 or not max_height or max_height <= 0:
tk_img = ImageTk.PhotoImage(img)
setattr(self, cache_attr, tk_img)
return tk_img
# Keep height fixed, force width wider (stretches horizontally)
new_h = max_height
new_w = 450 # <-- change this number to make it wider/narrower
img = img.resize((new_w, new_h), Image.LANCZOS)
tk_img = ImageTk.PhotoImage(img)
setattr(self, cache_attr, tk_img)
return tk_img
except Exception:
setattr(self, cache_attr, None)
return None
def _load_req_form_geometry(self) -> str | None:
try:
if os.path.exists(REQ_FORM_GEOM_FILE):
with open(REQ_FORM_GEOM_FILE, "r", encoding="utf-8") as f:
data = json.load(f) if f else {}
geom = data.get("geometry")
return geom if isinstance(geom, str) and "x" in geom else None
except Exception:
pass
return None
def _save_req_form_geometry(self, win: tk.Toplevel) -> None:
try:
with open(REQ_FORM_GEOM_FILE, "w", encoding="utf-8") as f:
json.dump({"geometry": win.geometry()}, f)
except Exception:
pass
def _apply_style(self):
style = ttk.Style()
try:
if "clam" in style.theme_names():
style.theme_use("clam")
except Exception:
pass
# Global backgrounds
style.configure("TFrame", background=LIGHT_BG)
style.configure("TLabelframe", background=LIGHT_BG)
style.configure("TLabelframe.Label", background=LIGHT_BG, font=("Segoe UI", 12, "bold"), foreground="#123B6F")
style.configure("TLabel", background=LIGHT_BG, foreground="#0F2D57")
style.configure("Status.TLabel", font=SUBHEADER_FONT, foreground="#234B7A", background=LIGHT_BG)
# Make all entry / combobox fields WHITE (instead of the default grey)
style.configure("TEntry", fieldbackground="white", background="white", foreground="#0F2D57")
style.configure("TCombobox", fieldbackground="white", background="white", foreground="#0F2D57")
style.map("TCombobox", fieldbackground=[("readonly", "white")], background=[("readonly", "white")])
# Buttons + tree
style.configure("Treeview", rowheight=30, font=TREE_FONT)
style.configure("Treeview.Heading", font=TREE_HEADING_FONT, background="#2A6BC0", foreground="white")
style.map("Treeview.Heading", background=[("active", "#174B8D")])
style.configure(
"Primary.TButton",
font=("Segoe UI", 12, "bold"),
padding=(10, 8),
foreground="white",
background=BLUE_PRIMARY,
)
style.map("Primary.TButton", background=[("active", "#174B8D"), ("pressed", "#123B6F")])
# Dedup checkbox (theme)
style.configure("Dedup.TCheckbutton", background=LIGHT_BG, foreground="#0F2D57")
style.configure("Queue.TCheckbutton", background=LIGHT_BG, foreground=BLUE_PRIMARY, font=("Segoe UI", 11, "bold"))
style.map("Queue.TCheckbutton", background=[("active", LIGHT_BG)], foreground=[("active", BLUE_PRIMARY)])
style.map("Dedup.TCheckbutton", background=[("active", LIGHT_BG)])
style.configure(
"BigPrimary.TButton",
font=BUTTON_FONT_BIG,
padding=(18, 12),
foreground="white",
background=BLUE_PRIMARY,
)
style.map("BigPrimary.TButton", background=[("active", "#174B8D"), ("pressed", "#123B6F")])
# Slightly larger "Request Software" button
style.configure("HugePrimary.TButton", font=("Segoe UI", 15, "bold"), padding=(22, 14), foreground="white", background=BLUE_PRIMARY)
style.map("HugePrimary.TButton", background=[("active", "#174B8D"), ("pressed", "#123B6F")])
style.configure("Secondary.TButton", font=("Segoe UI", 12, "bold"), padding=(10, 8), foreground="white", background="#2A6BC0")
style.map("Secondary.TButton", background=[("active", "#174B8D"), ("pressed", "#123B6F")])
# Notebook styling (reduce default grey)
style.configure("TNotebook", background=LIGHT_BG, borderwidth=0)
style.configure("TNotebook.Tab", background=LIGHT_BG_2, foreground="#0F2D57", padding=(12, 8))
style.map("TNotebook.Tab",
background=[("selected", BLUE_PRIMARY), ("active", "#2A6BC0")],
foreground=[("selected", "white"), ("active", "white")])
# Separators
style.configure("TSeparator", background=LIGHT_BG_2)
# Scrollbars (more blue-friendly)
style.configure("Vertical.TScrollbar", troughcolor=LIGHT_BG_2, background=BLUE_PRIMARY, bordercolor=LIGHT_BG_2, arrowcolor="#0F2D57")
style.configure("Horizontal.TScrollbar", troughcolor=LIGHT_BG_2, background=BLUE_PRIMARY, bordercolor=LIGHT_BG_2, arrowcolor="#0F2D57")
def _make_tree(self, parent):
frame = ttk.Frame(parent)
frame.pack(fill="both", expand=True)
frame.rowconfigure(0, weight=1)
frame.columnconfigure(0, weight=1)
tree = ttk.Treeview(frame, show="headings")
vsb = ttk.Scrollbar(frame, orient="vertical", command=tree.yview)
hsb = ttk.Scrollbar(frame, orient="horizontal", command=tree.xview)
tree.configure(yscrollcommand=vsb.set, xscrollcommand=hsb.set)
tree.grid(row=0, column=0, sticky="nsew")
vsb.grid(row=0, column=1, sticky="ns")
hsb.grid(row=1, column=0, sticky="ew")
tree.tag_configure("odd", background=ROW_ODD)
tree.tag_configure("even", background=ROW_EVEN)
return tree
def _configure_tree_columns(self, tree: ttk.Treeview, columns):
tree["columns"] = list(columns)
for c in columns:
tree.heading(c, text=c)
tree.column(c, width=160, anchor="w", stretch=True)
def _autosize_columns_to_content(self, tree: ttk.Treeview, max_rows_scan: int = 250):
cols = list(tree["columns"])
if not cols:
return
try:
import tkinter.font as tkfont
f = tkfont.Font(family=TREE_FONT[0], size=TREE_FONT[1])
except Exception:
f = None
def measure(text: str) -> int:
text = "" if text is None else str(text)
return f.measure(text) if f else int(len(text) * 7)
widths = {c: measure(c) + 28 for c in cols}
kids = tree.get_children()[:max_rows_scan]
for iid in kids:
vals = tree.item(iid, "values")
for c, v in zip(cols, vals):
widths[c] = max(widths[c], measure(v) + 28)
for c in cols:
w = widths[c]
cl = c.strip().lower()
if cl in ("description", "instructional need"):
w = min(max(w, 320), 950)
elif cl == "url":
w = min(max(w, 260), 650)
elif cl in ("attachments", "software assessments"):
w = min(max(w, 320), 950)
else:
w = min(max(w, 140), 480)
tree.column(c, width=w, stretch=True)
def _install_copy_shortcuts(self, tree: ttk.Treeview):
def select_all(_=None):
kids = tree.get_children()
if kids:
tree.selection_set(kids)
def copy_rows(_=None):
sel = tree.selection()
if not sel:
return
cols = list(tree["columns"])
lines = ["\t".join(cols)]
for iid in sel:
vals = tree.item(iid, "values")
lines.append("\t".join("" if v is None else str(v) for v in vals))
self.root.clipboard_clear()
self.root.clipboard_append("\n".join(lines))
tree.bind("<Control-a>", select_all)
tree.bind("<Control-A>", select_all)
tree.bind("<Control-c>", copy_rows)
tree.bind("<Control-C>", copy_rows)
def _find_col(self, df: pd.DataFrame, names_lower):
cols = {str(c).strip().lower(): c for c in df.columns}
for n in names_lower:
if n in cols:
return cols[n]
return None
def _find_sheet_case_insensitive(self, sheet_names, wanted: str):
wanted_l = wanted.strip().lower()
for s in sheet_names:
if str(s).strip().lower() == wanted_l:
return s
return None
def _build_ui(self):
main = ttk.Frame(self.root, style='TFrame')
main.grid(row=0, column=0, sticky="nsew")
main.rowconfigure(2, weight=1)
main.columnconfigure(0, weight=1)
header = ttk.Frame(main, padding=(16, 14, 16, 8))
header.grid(row=0, column=0, sticky="ew")
header.columnconfigure(0, weight=1)
ttk.Label(header, text="Software Search", font=HEADER_FONT).grid(row=0, column=0, sticky="w")
ttk.Label(header, text="Ctrl+C copy • Ctrl+A select all", font=SUBHEADER_FONT, foreground="#3A5E8C").grid(
row=1, column=0, sticky="w", pady=(2, 0)
)
wb_row = ttk.Frame(header)
wb_row.grid(row=0, column=1, rowspan=2, sticky="e")
ttk.Label(wb_row, text="Workbook:").grid(row=0, column=0, sticky="e", padx=(0, 6))
ttk.Entry(wb_row, textvariable=self.workbook_path, width=64).grid(row=0, column=1, padx=(0, 10), sticky="we")
ttk.Button(wb_row, text="Browse…", command=self.browse_workbook, style="Secondary.TButton").grid(row=0, column=2, padx=(0, 8))
ttk.Button(wb_row, text="Load", command=self.load_current_workbook, style="Primary.TButton").grid(
row=0, column=3, padx=(0, 10)
)
# ---- Controls row: left outlined "Search + Filters" + right "REQUEST SOFTWARE" (no outline) ----
# UI goal:
# - The outlined box should END after Search/Clear (no giant empty bordered area on wide windows).
# - The Request button should live OUTSIDE the outline and be easy to nudge horizontally.
controls_row = ttk.Frame(main)
controls_row.grid(row=1, column=0, sticky="ew", padx=16, pady=(6, 10))
# Lock the left two columns to content; let only the far-right spacer grow.
controls_row.columnconfigure(0, weight=0)
controls_row.columnconfigure(1, weight=0)
controls_row.columnconfigure(2, weight=1) # spacer eats extra width
controls = ttk.LabelFrame(controls_row, text="Search + Filters", padding=(14, 12))
# IMPORTANT: sticky="w" (NOT "ew") ensures the border never stretches across the window.
controls.grid(row=0, column=0, sticky="w")
request_area = ttk.Frame(controls_row)
# sticky="n" keeps the Request button vertically aligned with the Search/Clear stack.
request_area.grid(row=0, column=1, sticky="n", padx=(18, 0), pady=(2, 0))
# Right-side banner area (use the flexible spacer column) — place DoDEA logo here
logo_host = ttk.Frame(controls_row)
logo_host.grid(row=0, column=2, sticky="nsew")
# Manual placement knobs (0..1)
LOGO_RELX = 0.50
LOGO_RELY = 0.45
#if getattr(self, "_dodea_logo_main", None):
# logo_lbl = ttk.Label(logo_host, image=self._dodea_logo_main, background=LIGHT_BG)
# logo_lbl.image = self._dodea_logo_main
# logo_lbl.place(relx=LOGO_RELX, rely=LOGO_RELY, anchor="center")
# ---- Uniform spacing: build filter rows as equal-padding "field groups" ----
# NOTE: these are purely UI tuning knobs.
GROUP_PAD_X = 14
GROUP_PAD_Y = 2
LABEL_TO_WIDGET_PAD_Y = 4
def add_field_group(parent, col, label_text, widget_factory, *, group_padx=GROUP_PAD_X, group_pady=GROUP_PAD_Y):
g = ttk.Frame(parent)
g.grid(row=0, column=col, padx=(0, group_padx), pady=(0, group_pady), sticky="w")
ttk.Label(g, text=label_text).grid(row=0, column=0, sticky="w")
w = widget_factory(g)
w.grid(row=1, column=0, sticky="w", pady=(LABEL_TO_WIDGET_PAD_Y, 0))
return w
# Row 0: Name | Vendor | Platform | Approval | Expired
filters_row = ttk.Frame(controls)
filters_row.grid(row=0, column=0, sticky="w")
self.name_entry = add_field_group(filters_row, 0, "Name", lambda p: ttk.Entry(p, textvariable=self.name_query_var, width=30))
self.name_entry.bind("<Return>", lambda e: self.run_search())
self.vendor_combo = add_field_group(filters_row, 1, "Vendor", lambda p: ttk.Combobox(p, state="readonly", width=26, textvariable=self.vendor_filter))
self.vendor_combo.bind("<<ComboboxSelected>>", lambda e: self.run_search())
self.platform_combo = add_field_group(filters_row, 2, "Platform", lambda p: ttk.Combobox(p, state="readonly", width=18, textvariable=self.platform_filter))
self.platform_combo.bind("<<ComboboxSelected>>", lambda e: self.run_search())
self.state_combo = add_field_group(filters_row, 3, "Approval", lambda p: ttk.Combobox(p, state="readonly", width=16, textvariable=self.state_filter))
self.state_combo.bind("<<ComboboxSelected>>", lambda e: self.run_search())
self.status_combo = add_field_group(
filters_row,
4,
"Expired",
lambda p: ttk.Combobox(p, state="readonly", width=16, textvariable=self.status_filter),
group_padx=0, # last group (no extra right padding)
)
self.status_combo["values"] = ["(Any)", "Expired Only", "Not Expired Only"]
self.status_combo.bind("<<ComboboxSelected>>", lambda e: self.run_search())
# Row 1: Search field + Query
search_row = ttk.Frame(controls)
search_row.grid(row=1, column=0, sticky="w", pady=(10, 0))
self.field_combo = add_field_group(search_row, 0, "Search field", lambda p: ttk.Combobox(p, state="readonly", width=22, textvariable=self.search_field))
self.query_entry = add_field_group(search_row, 1, "Query", lambda p: ttk.Entry(p, textvariable=self.query_var, width=44), group_padx=0)
self.query_entry.bind("<Return>", lambda e: self.run_search())
ttk.Checkbutton(
controls,
text="Dedup by Product (show latest version)",
variable=self.dedup_var,
command=self.run_search,
style="Dedup.TCheckbutton",
).grid(row=2, column=0, pady=(10, 0), sticky="w")
# Layout behavior inside the outlined box:
# Keep everything tight and left-aligned. Do NOT add a stretching spacer inside the LabelFrame,
# otherwise wide windows look like a huge empty bordered area.
controls.columnconfigure(0, weight=0) # filters do NOT stretch horizontally
controls.columnconfigure(1, weight=0) # Search/Clear stack
# Action buttons area (right side)
# Search/Clear stack goes in the RED area; Request Software goes in the GREEN area (far right).
btns = ttk.Frame(controls)
# Pad from the last dropdown to the action buttons for a clean separation.
btns.grid(row=0, column=1, rowspan=2, padx=(18, 0), sticky="n")
ttk.Button(btns, text="Search", command=self.run_search, style="Primary.TButton", width=14).pack(pady=(0, 6))
ttk.Button(btns, text="Clear", command=self.clear_all, width=14, style="Primary.TButton").pack(pady=(0, 0))
# ---- Request button (outside the outline) ----
# Manual nudge control: change REQ_BTN_NUDGE_X to fine-tune placement.
REQ_BTN_NUDGE_X = 0
REQ_BTN_NUDGE_Y = 36
self.request_btn_inline = ttk.Button(
request_area, text="REQUEST SOFTWARE", command=self.open_request_form, style="HugePrimary.TButton"
)
self.request_btn_inline.grid(row=0, column=0, padx=(REQ_BTN_NUDGE_X, 0), pady=(REQ_BTN_NUDGE_Y, 0), sticky="w")
body = ttk.Frame(main, padding=(16, 0, 16, 12))
body.grid(row=2, column=0, sticky="nsew")
body.rowconfigure(0, weight=1)
body.columnconfigure(0, weight=1)
self.notebook = ttk.Notebook(body)
self.notebook.grid(row=0, column=0, sticky="nsew")
self.results_tab = ttk.Frame(self.notebook)
self.notebook.add(self.results_tab, text="Results")
top_status = ttk.Frame(self.results_tab, padding=(2, 8))
top_status.pack(fill="x")
self.status_var = tk.StringVar(value="Load a workbook to begin.")
ttk.Label(top_status, textvariable=self.status_var, style="Status.TLabel").pack(anchor="w")
# Results actions (UI-only)
results_actions = ttk.Frame(self.results_tab, padding=(2, 0, 2, 8))
results_actions.pack(fill="x")
results_actions.columnconfigure(0, weight=1)
self.results_delete_btn = ttk.Button(
results_actions,
text="Delete Selected",
command=self.delete_selected_result,
style="Secondary.TButton",
state="disabled",
)
self.results_delete_btn.grid(row=0, column=1, sticky="e")
self.results_clear_btn = ttk.Button(
results_actions,
text="Clear Results",
command=self.clear_results_table,
style="Secondary.TButton",
state="disabled",
)
self.results_clear_btn.grid(row=0, column=2, padx=(10, 0), sticky="e")
self.results_tree = self._make_tree(self.results_tab)
self._install_copy_shortcuts(self.results_tree)
# Enable/disable Results actions based on selection/content (UI-only)
self.results_tree.bind("<<TreeviewSelect>>", lambda e: self._update_results_buttons_state())
self.results_tree.bind("<Delete>", lambda e: self.delete_selected_result())
self._update_results_buttons_state()
self.queue_tab = ttk.Frame(self.notebook)
self.notebook.add(self.queue_tab, text="Request Queue")
queue_top = ttk.Frame(self.queue_tab, padding=(2, 8))
queue_top.pack(fill="x")
queue_top.columnconfigure(0, weight=1)
self.queue_status_var = tk.StringVar(value="No requests yet.")
ttk.Label(queue_top, textvariable=self.queue_status_var, style="Status.TLabel").grid(row=0, column=0, sticky="w")
queue_controls = ttk.Frame(self.queue_tab, padding=(2, 0, 2, 8))
queue_controls.pack(fill="x")
queue_controls.columnconfigure(1, weight=1)
ttk.Label(queue_controls, text="Queue Search:").grid(row=0, column=0, sticky="w", padx=(0, 8))
q_entry = ttk.Entry(queue_controls, textvariable=self.queue_query_var)
q_entry.grid(row=0, column=1, sticky="ew")
q_entry.bind("<Return>", lambda e: self.refresh_queue_table())
ttk.Button(queue_controls, text="Apply", command=self.refresh_queue_table, style="Primary.TButton").grid(
row=0, column=2, padx=(10, 0)
)
ttk.Button(queue_controls, text="Clear", command=self.clear_queue_filter, style="Primary.TButton", width=10).grid(row=0, column=3, padx=(10, 0))
ttk.Checkbutton(
queue_controls, text="Emergency Only", variable=self.queue_emergency_only_var, command=self.refresh_queue_table, style="Queue.TCheckbutton"
).grid(row=0, column=4, padx=(14, 0), sticky="w")
action_row = ttk.Frame(self.queue_tab, padding=(2, 0, 2, 8))
action_row.pack(fill="x")
action_row.columnconfigure(0, weight=1)
self.edit_req_btn = ttk.Button(action_row, text="Edit", command=self.edit_selected_request, style="Secondary.TButton")
self.edit_req_btn.grid(row=0, column=1, padx=(0, 10), sticky="e")
self.delete_req_btn = ttk.Button(action_row, text="Delete", command=self.delete_selected_request, style="Secondary.TButton")
self.delete_req_btn.grid(row=0, column=2, padx=(0, 10), sticky="e")
self.add_software_btn = ttk.Button(action_row, text="Add Software", command=self.add_selected_request_to_all, style="Primary.TButton")
self.add_software_btn.grid(row=0, column=3, padx=(0, 10), sticky="e")
ttk.Button(action_row, text="Export Queue (EDRL Format)", command=self.export_queue_edrl, style="Secondary.TButton").grid(
row=0, column=4, padx=(8, 0), sticky="e"
)
self.queue_tree = self._make_tree(self.queue_tab)
self._install_copy_shortcuts(self.queue_tree)
self._configure_tree_columns(self.queue_tree, self.queue_columns_display)
self.queue_tree.bind("<<TreeviewSelect>>", lambda e: self._update_queue_buttons_state())
self._update_queue_buttons_state()
# workbook
def browse_workbook(self):
path = filedialog.askopenfilename(title="Select workbook", filetypes=[("Excel files", "*.xlsx *.xls"), ("All files", "*.*")])
if path:
self.workbook_path.set(path)
def load_current_workbook(self):
path = (self.workbook_path.get() or "").strip().strip('"')
if not path:
messagebox.showerror("Error", "Please select a workbook.")
return
self.load_workbook(path)
def load_workbook(self, path: str):
try:
xls = pd.ExcelFile(path)
sheet_names = xls.sheet_names
self.sheets = {s: pd.read_excel(path, sheet_name=s, dtype=str).fillna("") for s in sheet_names}
self.idx_sheets = {s: self.build_index(df) for s, df in self.sheets.items()}
all_sheet = self._find_sheet_case_insensitive(sheet_names, "All") or sheet_names[0]
preferred = []
for candidate in ["All", "Cloud", "Chrome_AppExt", "Software", "Mobile", "Everything Else"]:
real = self._find_sheet_case_insensitive(sheet_names, candidate)
if real and real not in preferred:
preferred.append(real)
ordered = preferred + [s for s in sheet_names if s not in preferred]
if hasattr(self, "sheet_combo"):
self.sheet_combo["values"] = ordered
self.current_sheet.set(all_sheet)
self.on_sheet_change()
self.status_var.set(f"Loaded: {os.path.basename(path)} • Tabs: {len(sheet_names)}")
except Exception as e:
messagebox.showerror("Load failed", f"Could not load workbook.\n\n{e}")
def build_index(self, df: pd.DataFrame) -> pd.DataFrame:
idx = df.copy()
idx["_blob"] = df.astype(str).agg(" ".join, axis=1).map(norm_text)
exp_col = self._find_col(df, ["authorization expires", "authorization expiration", "authorization expiration date", "authorization expires date", "authorization expiration (date)"])
idx["is_expired"] = False
if exp_col:
exp_dt = pd.to_datetime(df[exp_col], errors="coerce")
now = pd.Timestamp.now().normalize()
idx["is_expired"] = exp_dt.notna() & (exp_dt < now)
name_col = self._find_col(df, ["name"])
vendor_col = self._find_col(df, ["vendor"])
platform_col = self._find_col(df, ["platform"])
version_col = self._find_col(df, ["version"])
name_s = df[name_col].astype(str) if name_col else pd.Series([""] * len(df))
vendor_s = df[vendor_col].astype(str) if vendor_col else pd.Series([""] * len(df))
platform_s = df[platform_col].astype(str) if platform_col else pd.Series([""] * len(df))
version_s = df[version_col].astype(str) if version_col else pd.Series([""] * len(df))
idx["name_norm"] = name_s.map(norm_text)
idx["vendor_norm"] = vendor_s.map(norm_text)
idx["platform_norm"] = platform_s.map(norm_text)
idx["version_norm"] = version_s.map(extract_version_norm)
idx["product_key"] = idx["vendor_norm"] + "|" + idx["name_norm"] + "|" + idx["platform_norm"]
state_col = self._find_col(df, ["state"])
idx["state_norm"] = ""
if state_col:
idx["state_norm"] = df[state_col].astype(str).map(normalize_state)
return idx
def dedup_latest(self, idx: pd.DataFrame, original: pd.DataFrame) -> pd.DataFrame:
if "product_key" not in idx.columns or "version_norm" not in idx.columns:
return original
idx_sorted = idx.sort_values(["product_key", "version_norm"], ascending=[True, False])
top = idx_sorted.groupby("product_key", as_index=False).head(1)
return original.loc[top.index].copy()
# search
def on_sheet_change(self):
sheet = self.current_sheet.get()
if sheet not in self.sheets:
return
df = self.sheets[sheet]
idx = self.idx_sheets[sheet]
self.field_combo["values"] = ["All searchable fields"] + list(df.columns)
self.search_field.set("All searchable fields")
vendor_col = self._find_col(df, ["vendor"])
platform_col = self._find_col(df, ["platform"])
state_col = self._find_col(df, ["state"])
self.vendor_combo["values"] = ["(Any)"] + (sorted({str(v).strip() for v in df[vendor_col].astype(str).tolist() if str(v).strip()}) if vendor_col else [])
self.platform_combo["values"] = ["(Any)"] + (sorted({str(p).strip() for p in df[platform_col].astype(str).tolist() if str(p).strip()}) if platform_col else [])
if state_col and "state_norm" in idx.columns:
present = set([s for s in idx["state_norm"].astype(str).tolist() if s])
vals = ["(Any)"]
if "approved" in present:
vals.append("Approved")
if "not approved" in present:
vals.append("Not Approved")
if vals == ["(Any)"]:
vals = ["(Any)", "Approved", "Not Approved"]
self.state_combo["values"] = vals
else:
self.state_combo["values"] = ["(Any)"]
self.vendor_filter.set("(Any)")
self.platform_filter.set("(Any)")
self.status_filter.set("(Any)")
self.state_filter.set("(Any)")
self.run_search()
def run_search(self):
sheet = self.current_sheet.get()
if sheet not in self.sheets:
return
df = self.sheets[sheet]
idx = self.idx_sheets[sheet]
query = (self.query_var.get() or "").strip()
name_query = (self.name_query_var.get() or "").strip()
vendor_sel = self.vendor_filter.get()
platform_sel = self.platform_filter.get()
status_sel = self.status_filter.get()
state_sel = self.state_filter.get()
field_sel = self.search_field.get()
vendor_col = self._find_col(df, ["vendor"])
platform_col = self._find_col(df, ["platform"])
name_col = self._find_col(df, ["name"])
mask = pd.Series(True, index=df.index)
if vendor_col and vendor_sel != "(Any)":
mask &= df[vendor_col].astype(str).str.strip().eq(vendor_sel)
if platform_col and platform_sel != "(Any)":
mask &= df[platform_col].astype(str).str.strip().eq(platform_sel)
if state_sel in {"Approved", "Not Approved"} and "state_norm" in idx.columns:
want = "approved" if state_sel == "Approved" else "not approved"
mask &= idx["state_norm"].astype(str).str.strip().eq(want)
if status_sel == "Expired Only":
mask &= idx["is_expired"].astype(bool)
elif status_sel == "Not Expired Only":
mask &= ~idx["is_expired"].astype(bool)
if name_query:
if name_col:
mask &= df[name_col].astype(str).str.contains(name_query, case=False, na=False)
else:
mask &= idx["_blob"].astype(str).str.contains(norm_text(name_query), na=False)
if query:
if field_sel == "All searchable fields":
mask &= idx["_blob"].astype(str).str.contains(norm_text(query), na=False)
elif field_sel in df.columns:
mask &= df[field_sel].astype(str).str.contains(query, case=False, na=False)
results = df.loc[mask].copy()
if self.dedup_var.get():
results = self.dedup_latest(idx.loc[mask], results)
self.populate_results_table(results)
def clear_all(self):
self.query_var.set("")
self.name_query_var.set("")
self.vendor_filter.set("(Any)")
self.platform_filter.set("(Any)")
self.status_filter.set("(Any)")