-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdialogs.py
More file actions
504 lines (409 loc) · 20.6 KB
/
dialogs.py
File metadata and controls
504 lines (409 loc) · 20.6 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
"""
Dialog Windows for Transaction Manager
Contains CSV import dialog and category filter dialog
"""
import tkinter as tk
from tkinter import ttk, messagebox
import os
from typing import Optional, Set, List, Dict, Any
from theme import Theme, apply_theme_to_toplevel
class CSVImportDialog(tk.Toplevel):
"""Dialog for configuring CSV import settings"""
def __init__(self, parent: tk.Tk, csv_file_path: str, importer,
theme: Theme, settings_manager, db):
"""
Initialize CSV Import Dialog
Args:
parent: Parent tkinter window
csv_file_path: Path to CSV file to import
importer: TransactionImporter instance
theme: Theme instance for styling
settings_manager: ImportSettings instance
db: TransactionDB instance for account management
"""
super().__init__(parent)
self.csv_file_path = csv_file_path
self.importer = importer
self.result: Optional[Dict[str, Any]] = None
self.theme = theme
self.settings_manager = settings_manager
self.db = db
self.title("Configure CSV Import")
self.geometry("900x700")
self.state('zoomed') # Open maximized/fullscreen
self.minsize(800, 600) # Set minimum size to ensure all controls are visible
self.grab_set()
# Apply theme to this window
apply_theme_to_toplevel(self, theme)
self.skip_lines_var = tk.IntVar(value=0)
self.all_columns: List[str] = [] # Will store all column names for hashing
self.csv_columns: List[str] = [] # CSV file columns
self.column_mapping: Dict[str, tk.StringVar] = {} # Mapping vars
self.account_var = tk.StringVar() # Selected account name
self.accounts: List[Dict] = [] # Available accounts
# Try to load saved settings for this CSV
self.saved_settings = self.settings_manager.get_settings_for_csv(csv_file_path)
if self.saved_settings:
self.skip_lines_var.set(self.saved_settings.get('skip_lines', 0))
self.setup_ui()
self.update_preview()
def setup_ui(self):
"""Setup the dialog UI"""
# File info
info_frame = ttk.LabelFrame(self, text="File Information", padding="10")
info_frame.pack(fill=tk.X, padx=10, pady=5)
ttk.Label(info_frame, text=f"File: {os.path.basename(self.csv_file_path)}",
font=('Arial', 10, 'bold')).pack(anchor=tk.W)
# Account selection frame
account_frame = ttk.LabelFrame(self, text="Step 1: Select Account", padding="10")
account_frame.pack(fill=tk.X, padx=10, pady=5)
# Load accounts
self.accounts = self.db.get_all_accounts()
# Account selection controls
account_select_frame = ttk.Frame(account_frame)
account_select_frame.pack(fill=tk.X, pady=5)
ttk.Label(account_select_frame, text="Import to account:").pack(side=tk.LEFT, padx=(0, 10))
account_combo = ttk.Combobox(account_select_frame, textvariable=self.account_var,
state='readonly', width=30)
account_combo['values'] = [acc['name'] for acc in self.accounts]
if self.accounts:
self.account_var.set(self.accounts[0]['name']) # Select first account by default
account_combo.pack(side=tk.LEFT, padx=(0, 10))
ttk.Button(account_select_frame, text="+ New Account",
command=self.create_new_account).pack(side=tk.LEFT)
# Configuration frame
config_frame = ttk.LabelFrame(self, text="Step 2: Import Configuration", padding="10")
config_frame.pack(fill=tk.X, padx=10, pady=5)
# Skip lines
skip_frame = ttk.Frame(config_frame)
skip_frame.pack(fill=tk.X, pady=5)
ttk.Label(skip_frame, text="Lines to skip before header:").pack(side=tk.LEFT, padx=(0, 10))
skip_spinbox = ttk.Spinbox(skip_frame, from_=0, to=20, textvariable=self.skip_lines_var,
width=5, command=self.update_preview)
skip_spinbox.pack(side=tk.LEFT)
muted_label = ttk.Label(skip_frame, text="(Use this if your CSV has extra rows before the column headers)")
muted_label.configure(foreground=self.theme.get_color('text_muted'))
muted_label.pack(side=tk.LEFT, padx=10)
# Preview frame
preview_frame = ttk.LabelFrame(self, text="CSV Preview (First 5 Rows)", padding="10")
preview_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=5)
# Preview treeview
tree_frame = ttk.Frame(preview_frame)
tree_frame.pack(fill=tk.BOTH, expand=True)
scroll_y = ttk.Scrollbar(tree_frame)
scroll_y.pack(side=tk.RIGHT, fill=tk.Y)
scroll_x = ttk.Scrollbar(tree_frame, orient=tk.HORIZONTAL)
scroll_x.pack(side=tk.BOTTOM, fill=tk.X)
self.preview_tree = ttk.Treeview(tree_frame,
yscrollcommand=scroll_y.set,
xscrollcommand=scroll_x.set,
selectmode='none')
scroll_y.config(command=self.preview_tree.yview)
scroll_x.config(command=self.preview_tree.xview)
self.preview_tree.pack(fill=tk.BOTH, expand=True)
# Column mapping frame
mapping_frame = ttk.LabelFrame(self, text="Step 3: Map Columns", padding="10")
mapping_frame.pack(fill=tk.X, padx=10, pady=5)
ttk.Label(mapping_frame,
text="Map your CSV columns to standard fields. Auto-detected mappings are shown below.",
font=('Arial', 9)).pack(anchor=tk.W, pady=(0, 10))
# Create mapping controls
self.mapping_widgets = {}
self.create_mapping_controls(mapping_frame)
# Duplicate detection info
dup_frame = ttk.LabelFrame(self, text="Duplicate Detection", padding="10")
dup_frame.pack(fill=tk.X, padx=10, pady=5)
ttk.Label(dup_frame,
text="✓ Duplicate detection uses the entire CSV line for comparison",
font=('Arial', 9)).pack(anchor=tk.W, pady=(0, 5))
ttk.Label(dup_frame,
text="This ensures exact duplicate detection - if any field differs, it will be imported.",
font=('Arial', 9)).pack(anchor=tk.W)
# Buttons frame
btn_frame = ttk.Frame(self)
btn_frame.pack(fill=tk.X, padx=10, pady=10)
ttk.Button(btn_frame, text="Cancel", command=self.cancel).pack(side=tk.RIGHT, padx=2)
ttk.Button(btn_frame, text="Import", command=self.do_import,
style='Accent.TButton').pack(side=tk.RIGHT, padx=2)
def update_preview(self):
"""Update the CSV preview"""
skip_lines = self.skip_lines_var.get()
# Get preview
headers, sample_rows, errors = self.importer.get_csv_preview(
self.csv_file_path, skip_lines, 5
)
if errors:
messagebox.showerror("Preview Error", "\n".join(errors))
return
# Clear previous preview
self.preview_tree.delete(*self.preview_tree.get_children())
# Set up columns
if headers:
self.preview_tree['columns'] = headers
self.preview_tree['show'] = 'headings'
for col in headers:
self.preview_tree.heading(col, text=col)
self.preview_tree.column(col, width=100)
# Add sample rows
for row in sample_rows:
self.preview_tree.insert('', tk.END, values=row)
# Store all columns for hash calculation
if headers:
self.all_columns = headers
self.csv_columns = headers
self.update_mapping_controls()
def create_mapping_controls(self, parent):
"""Create column mapping dropdown controls"""
self.mapping_container = ttk.Frame(parent)
self.mapping_container.pack(fill=tk.X)
# Will be populated when CSV is loaded
ttk.Label(self.mapping_container,
text="(Mappings will appear after CSV preview loads)",
foreground='gray').pack()
def update_mapping_controls(self):
"""Update mapping controls with detected columns"""
# Clear existing
for widget in self.mapping_container.winfo_children():
widget.destroy()
# Auto-detect mapping
csv_columns, suggested_mapping = self.importer.auto_detect_columns(
self.csv_file_path,
self.skip_lines_var.get()
)
if not csv_columns:
return
# Define fields to map (required and common optional ones)
fields_to_map = [
('date', 'Date *', True),
('description', 'Description *', True),
('amount', 'Amount (single column)', False),
('amount_debit', 'Debit/Withdrawal', False),
('amount_credit', 'Credit/Deposit', False),
('memo', 'Memo/Notes', False),
('balance', 'Balance', False),
]
# Create a grid for mapping
for idx, (field_name, field_label, is_required) in enumerate(fields_to_map):
row_frame = ttk.Frame(self.mapping_container)
row_frame.pack(fill=tk.X, pady=2)
# Field label
label_text = field_label
ttk.Label(row_frame, text=label_text, width=25).pack(side=tk.LEFT, padx=(0, 10))
# Dropdown for CSV column
var = tk.StringVar(value=suggested_mapping.get(field_name, ''))
combo = ttk.Combobox(row_frame, textvariable=var, state='readonly', width=30)
combo['values'] = [''] + csv_columns
combo.pack(side=tk.LEFT)
self.column_mapping[field_name] = var
# Add validation note
note_frame = ttk.Frame(self.mapping_container)
note_frame.pack(fill=tk.X, pady=(10, 0))
note_label = ttk.Label(note_frame,
text="* Required fields | Must map either 'Amount' OR both 'Debit' and 'Credit'",
font=('Arial', 8))
note_label.configure(foreground=self.theme.get_color('text_muted'))
note_label.pack(anchor=tk.W)
def get_column_mapping(self) -> Dict[str, str]:
"""Get the current column mapping"""
mapping = {}
for field, var in self.column_mapping.items():
value = var.get()
if value: # Only include if a column is selected
mapping[field] = value
return mapping
def create_new_account(self):
"""Create a new account"""
dialog = tk.Toplevel(self)
dialog.title("Create New Account")
dialog.geometry("400x350")
dialog.minsize(400, 350)
dialog.transient(self)
dialog.grab_set()
apply_theme_to_toplevel(dialog, self.theme)
# Account name
ttk.Label(dialog, text="Account Name: *", font=('Arial', 10)).pack(anchor=tk.W, padx=10, pady=(10, 0))
name_var = tk.StringVar()
ttk.Entry(dialog, textvariable=name_var, width=40).pack(padx=10, pady=5)
# Institution
ttk.Label(dialog, text="Institution:", font=('Arial', 10)).pack(anchor=tk.W, padx=10, pady=(10, 0))
institution_var = tk.StringVar()
ttk.Entry(dialog, textvariable=institution_var, width=40).pack(padx=10, pady=5)
# Account type
ttk.Label(dialog, text="Account Type:", font=('Arial', 10)).pack(anchor=tk.W, padx=10, pady=(10, 0))
type_var = tk.StringVar()
type_combo = ttk.Combobox(dialog, textvariable=type_var, width=37, state='readonly')
type_combo['values'] = ['Checking', 'Savings', 'Credit Card', 'Investment', 'Other']
type_combo.pack(padx=10, pady=5)
# Description
ttk.Label(dialog, text="Description:", font=('Arial', 10)).pack(anchor=tk.W, padx=10, pady=(10, 0))
description_var = tk.StringVar()
ttk.Entry(dialog, textvariable=description_var, width=40).pack(padx=10, pady=5)
def save_account():
name = name_var.get().strip()
if not name:
messagebox.showerror("Error", "Account name is required")
return
# Add account to database
account_id = self.db.add_account(
name=name,
description=description_var.get().strip(),
institution=institution_var.get().strip(),
account_type=type_var.get()
)
if account_id:
# Refresh accounts list
self.accounts = self.db.get_all_accounts()
# Update the combo box (find the combobox widget)
for widget in self.winfo_children():
if isinstance(widget, ttk.LabelFrame) and "Step 1" in widget.cget('text'):
for child in widget.winfo_children():
if isinstance(child, ttk.Frame):
for subchild in child.winfo_children():
if isinstance(subchild, ttk.Combobox):
subchild['values'] = [acc['name'] for acc in self.accounts]
self.account_var.set(name)
break
messagebox.showinfo("Success", f"Account '{name}' created successfully!")
dialog.destroy()
else:
messagebox.showerror("Error", "Failed to create account")
# Buttons
btn_frame = ttk.Frame(dialog)
btn_frame.pack(pady=20)
ttk.Button(btn_frame, text="Cancel", command=dialog.destroy).pack(side=tk.LEFT, padx=5)
ttk.Button(btn_frame, text="Create", command=save_account, style='Accent.TButton').pack(side=tk.LEFT, padx=5)
def do_import(self):
"""Perform the import"""
# Validate account selection
account_name = self.account_var.get()
if not account_name:
messagebox.showwarning("No Account", "Please select an account")
return
# Get account ID
account = self.db.get_account_by_name(account_name)
if not account:
messagebox.showerror("Error", "Selected account not found")
return
# Use all columns for hash (entire line)
if not self.all_columns:
messagebox.showwarning("No Columns",
"Could not detect columns in CSV file.")
return
# Get and validate column mapping
column_mapping = self.get_column_mapping()
is_valid, errors = self.importer.column_mapper.validate_mapping(column_mapping)
if not is_valid:
messagebox.showerror("Invalid Mapping",
"Please fix the following issues:\n\n" + "\n".join(errors))
return
# Save settings for this CSV file (just skip_lines now)
self.settings_manager.save_settings_for_csv(
self.csv_file_path,
self.skip_lines_var.get(),
self.all_columns, # Use all columns for hash
self.all_columns
)
self.result = {
'skip_lines': self.skip_lines_var.get(),
'hash_columns': self.all_columns, # Use all columns
'verbose': False, # Removed debug checkbox
'column_mapping': column_mapping,
'account_id': account['id']
}
self.destroy()
def cancel(self):
"""Cancel the import"""
self.result = None
self.destroy()
class CategoryFilterDialog(tk.Toplevel):
"""Dialog for selecting multiple categories to filter"""
def __init__(self, parent: tk.Tk, db, theme: Theme,
selected_categories: Set[str], callback):
"""
Initialize Category Filter Dialog
Args:
parent: Parent tkinter window
db: TransactionDB instance
theme: Theme instance for styling
selected_categories: Set of currently selected category names
callback: Function to call with new selection
"""
super().__init__(parent)
self.db = db
self.theme = theme
self.selected_categories = selected_categories.copy()
self.callback = callback
self.title("Select Categories")
self.geometry("450x600")
self.minsize(400, 400) # Set minimum size
self.transient(parent)
self.grab_set()
# Apply theme to this window
apply_theme_to_toplevel(self, theme)
self.checkbox_vars: Dict[str, tk.BooleanVar] = {}
self.setup_ui()
def setup_ui(self):
"""Setup the dialog UI"""
# Main container with proper weight
self.grid_rowconfigure(1, weight=1) # Make middle section expandable
self.grid_columnconfigure(0, weight=1)
# Info label
info_frame = ttk.Frame(self, padding="10")
info_frame.grid(row=0, column=0, sticky="ew", padx=0, pady=0)
ttk.Label(info_frame, text="Select one or more categories to filter:",
font=('Arial', 10, 'bold')).pack(anchor=tk.W)
# Scrollable frame for checkboxes with proper sizing
list_frame = ttk.LabelFrame(self, text="Categories", padding="5")
list_frame.grid(row=1, column=0, sticky="nsew", padx=10, pady=5)
list_frame.grid_rowconfigure(0, weight=1)
list_frame.grid_columnconfigure(0, weight=1)
# Create scrollable area
canvas = tk.Canvas(list_frame, bg=self.theme.get_color('bg'), highlightthickness=0)
scrollbar = ttk.Scrollbar(list_frame, orient="vertical", command=canvas.yview)
scrollable_frame = ttk.Frame(canvas)
scrollable_frame.bind(
"<Configure>",
lambda e: canvas.configure(scrollregion=canvas.bbox("all"))
)
canvas.create_window((0, 0), window=scrollable_frame, anchor="nw")
canvas.configure(yscrollcommand=scrollbar.set)
# Grid layout for canvas and scrollbar
canvas.grid(row=0, column=0, sticky="nsew")
scrollbar.grid(row=0, column=1, sticky="ns")
# Get all categories
categories = self.db.get_all_categories()
# "All Categories" checkbox
all_var = tk.BooleanVar(value=len(self.selected_categories) == 0)
all_cb = ttk.Checkbutton(scrollable_frame, text="All Categories", variable=all_var,
command=lambda: self.toggle_all_categories(all_var))
all_cb.pack(anchor=tk.W, padx=5, pady=3)
ttk.Separator(scrollable_frame, orient='horizontal').pack(fill=tk.X, padx=5, pady=5)
# Individual category checkboxes
for cat in sorted(categories, key=lambda x: x['name']):
var = tk.BooleanVar(value=cat['name'] in self.selected_categories)
self.checkbox_vars[cat['name']] = var
cb = ttk.Checkbutton(scrollable_frame, text=cat['name'], variable=var)
cb.pack(anchor=tk.W, padx=5, pady=2)
# Buttons frame - always at bottom
btn_frame = ttk.Frame(self, padding="10")
btn_frame.grid(row=2, column=0, sticky="ew", padx=0, pady=0)
def clear_all():
for var in self.checkbox_vars.values():
var.set(False)
all_var.set(True)
ttk.Button(btn_frame, text="Clear All", command=clear_all).pack(side=tk.LEFT, padx=2)
ttk.Button(btn_frame, text="Cancel", command=self.destroy).pack(side=tk.RIGHT, padx=2)
ttk.Button(btn_frame, text="Apply", command=self.apply_filter,
style='Accent.TButton').pack(side=tk.RIGHT, padx=2)
def toggle_all_categories(self, all_var: tk.BooleanVar):
"""Toggle all categories when 'All Categories' is checked"""
if all_var.get():
for var in self.checkbox_vars.values():
var.set(False)
def apply_filter(self):
"""Apply the selected filters"""
# Get selected categories
self.selected_categories = {name for name, var in self.checkbox_vars.items() if var.get()}
# Call the callback with the new selection
self.callback(self.selected_categories)
self.destroy()