-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInventory_Manager.py
2084 lines (1762 loc) · 90.7 KB
/
Inventory_Manager.py
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 tkinter as tk
from tkinter import *
from tkinter import ttk
import tkinter.messagebox as messagebox
import sv_ttk
import sqlite3
from tkinter import filedialog
from openpyxl import Workbook
from openpyxl.styles import Font, Alignment
from openpyxl.utils import get_column_letter
import os
import csv
def backup_database():
# Connect to SQLite database
db_file = 'inventory.db'
conn = sqlite3.connect(db_file)
cursor = conn.cursor()
# Ask user to select a file for export
export_file_path = filedialog.asksaveasfilename(defaultextension=".bak", initialfile="backup.bak", filetypes=[("Backup files", "*.bak")])
if export_file_path:
try:
# Execute query to gather required data
cursor.execute('''SELECT Inventory.Description, Vendors.VendorName, Vendors.RepName, Vendors.RepPhone, Vendors.Discontinued,
Location.Location, Location.SubLocation, Location.Discontinued,
Inventory.Quantity, Inventory.ReorderLevel, Inventory.Cost, Inventory.Sell, Inventory.Discontinued
FROM Inventory
INNER JOIN Vendors ON Inventory.VendorID = Vendors.VendorID
INNER JOIN Location ON Inventory.LocationID = Location.LocationID''')
data = cursor.fetchall()
# Write data to CSV file
with open(export_file_path, 'w', newline='') as csv_file:
csv_writer = csv.writer(csv_file)
# Write header
csv_writer.writerow(['Description', 'VendorName', 'RepName', 'RepPhone', 'VendorDiscontinued',
'Location', 'SubLocation', 'LocationDiscontinued',
'Quantity', 'ReorderLevel', 'Cost', 'Sell', 'InventoryDiscontinued'])
# Write data
csv_writer.writerows(data)
messagebox.showinfo("Success", f"Database records successfully backed up to: {export_file_path}")
except Exception as e:
messagebox.showerror("Error", f"An error occurred during backup: {str(e)}")
# Close database connection
conn.close()
def restore_database():
# Connect to SQLite database
db_file = 'inventory.db'
conn = sqlite3.connect(db_file)
cursor = conn.cursor()
# Ask user to select the CSV file for import
import_file_path = filedialog.askopenfilename(filetypes=[("Backup files", "*.bak")])
if import_file_path:
try:
# Read data from CSV file
with open(import_file_path, 'r', newline='') as csv_file:
csv_reader = csv.reader(csv_file)
next(csv_reader) # Skip header
for row in csv_reader:
# Extract data from each row
description, vendor_name, rep_name, rep_phone, vendor_discontinued, location, sub_location, location_discontinued, \
quantity, reorder_level, cost, sell, inventory_discontinued = row
# Check if the vendor already exists in the database
cursor.execute("SELECT VendorID FROM Vendors WHERE VendorName=?", (vendor_name,))
vendor_id = cursor.fetchone()
if vendor_id:
vendor_id = vendor_id[0]
else:
# Insert new vendor into Vendors table
cursor.execute("INSERT INTO Vendors (VendorName, RepName, RepPhone, Discontinued) VALUES (?, ?, ?, ?)",
(vendor_name, rep_name, rep_phone, vendor_discontinued))
vendor_id = cursor.lastrowid
# Check if the location already exists in the database
cursor.execute("SELECT LocationID FROM Location WHERE Location=? AND SubLocation=?", (location,sub_location,))
location_id = cursor.fetchone()
if location_id:
location_id = location_id[0]
else:
# Insert new location into Location table
cursor.execute("INSERT INTO Location (Location, SubLocation, Discontinued) VALUES (?, ?, ?)",
(location, sub_location, location_discontinued))
location_id = cursor.lastrowid
# Insert inventory data into Inventory table
cursor.execute('''INSERT INTO Inventory (Description, VendorID, LocationID, Quantity, ReorderLevel, Cost, Sell, Discontinued)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)''',
(description, vendor_id, location_id, quantity, reorder_level, cost, sell, inventory_discontinued))
messagebox.showinfo("Success", f"Data successfully restored from: {import_file_path}")
except Exception as e:
messagebox.showerror("Error", f"An error occurred during restore: {str(e)}")
# Rollback changes if any error occurs
conn.rollback()
# Commit changes and close database connection
conn.commit()
conn.close()
populate_treeview()
def create_import_file():
file_path = filedialog.asksaveasfilename(defaultextension=".csv", initialfile="import_template.csv", filetypes=[("CSV files", "*.csv")])
if file_path:
# Define header rows
headers = ['Description', 'Vendor', 'RepName', 'RepPhone', 'Location', 'SubLocation', 'Quantity', 'ReorderLevel', 'Cost', 'Sell']
# Write headers to import.csv
with open(file_path, 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(headers)
messagebox.showinfo("Success", f"Import template file created at: {file_path}")
def import_records():
# Ask user to select file for opening
file_path = filedialog.askopenfilename(defaultextension=".csv", filetypes=[("CSV files", "*.csv")])
if not file_path:
return
# Connect to the SQLite database
conn = sqlite3.connect('inventory.db')
cursor = conn.cursor()
# Read data from CSV file and populate Vendors, Locations, and Items tables
with open(file_path, 'r', newline='') as csv_file:
csv_reader = csv.DictReader(csv_file)
for row in csv_reader:
description = row['Description']
vendor_name = row['Vendor']
repname = row['RepName']
repphone= row['RepPhone']
location_name = row['Location']
sub_location = row['SubLocation']
quantity = int(row['Quantity'].replace(',', '').strip())
reorder_level = int(row['ReorderLevel'].replace(',', '').strip())
cost = int(float(row['Cost'].replace(',', '').replace('$', '')) * 100)
sell = int(float(row['Sell'].replace(',', '').replace('$', '')) * 100)
# Check if vendor already exists
cursor.execute("SELECT VendorID FROM Vendors WHERE VendorName=?", (vendor_name,))
vendor_id = cursor.fetchone()
if vendor_id is None:
cursor.execute("INSERT INTO Vendors (VendorName, RepName, RepPhone, Discontinued) VALUES (?, ?, ?, 'N')", (vendor_name,repname,repphone,))
vendor_id = cursor.lastrowid
else:
vendor_id = vendor_id[0]
# Check if location already exists
cursor.execute("SELECT LocationID FROM Location WHERE Location=? AND SubLocation=?", (location_name, sub_location))
location_id = cursor.fetchone()
if location_id is None:
cursor.execute("INSERT INTO Location (Location, SubLocation, Discontinued) VALUES (?, ?, 'N')", (location_name, sub_location))
location_id = cursor.lastrowid
else:
location_id = location_id[0]
# Insert item into Items table
cursor.execute("INSERT INTO Inventory (Description, VendorID, LocationID, Quantity, ReorderLevel, Cost, Sell, Discontinued) VALUES (?, ?, ?, ?, ?, ?, ?, 'N')",
(description, vendor_id, location_id, quantity, reorder_level, cost, sell))
# Commit changes and close connection
conn.commit()
conn.close()
populate_treeview()
def check_database():
db_file = 'inventory.db'
# Check if the database file exists
if not os.path.exists(db_file):
# Connect to SQLite database (or create it if it doesn't exist)
conn = sqlite3.connect(db_file)
cursor = conn.cursor()
# Create Vendors table
cursor.execute('''CREATE TABLE IF NOT EXISTS Vendors (
VendorID INTEGER UNIQUE PRIMARY KEY AUTOINCREMENT,
VendorName TEXT NOT NULL,
RepName TEXT,
RepPhone TEXT,
Discontinued INTEGER
)''')
# Create Location table
cursor.execute('''CREATE TABLE IF NOT EXISTS Location (
LocationID INTEGER UNIQUE PRIMARY KEY AUTOINCREMENT,
Location TEXT NOT NULL,
SubLocation TEXT,
Discontinued INTEGER
)''')
# Create Inventory table
cursor.execute('''CREATE TABLE IF NOT EXISTS Inventory (
ItemID INTEGER UNIQUE PRIMARY KEY AUTOINCREMENT,
Description TEXT NOT NULL,
VendorID INTEGER,
LocationID INTEGER,
Quantity INTEGER,
ReorderLevel INTEGER,
Cost REAL,
Sell REAL,
Discontinued INTEGER,
FOREIGN KEY (VendorID) REFERENCES Vendors(VendorID),
FOREIGN KEY (LocationID) REFERENCES Location(LocationID)
)''')
# Create Settings table
cursor.execute('''CREATE TABLE IF NOT EXISTS Settings (
Purpose TEXT NOT NULL,
DiscName1 TEXT,
Discount1 INTEGER,
DiscName2 TEXT,
Discount2 INTEGER,
DiscName3 TEXT,
Discount3 INTEGER
)''')
default_values = ("Discounts", "10% Off", 10, "15% Off", 15, "20% Off", 20)
cursor.execute('''INSERT INTO Settings (Purpose, DiscName1, Discount1, DiscName2, Discount2, DiscName3, Discount3) VALUES (?, ?, ?, ?, ?, ?, ?)''', default_values)
# Commit changes and close connection
conn.commit()
conn.close()
def center_window(window, width, height):
screen_width = window.winfo_screenwidth()
screen_height = window.winfo_screenheight()
# Calculate the position of the window
x = max((screen_width - width) // 2, 0)
y = max((screen_height - height) // 2 - 25, 0) # Adjusting for window decorations
# Set the geometry of the window to center it on the screen
window.geometry(f"{width}x{height}+{x}+{y}")
window.minsize(width, height)
def get_mapped_value(input_value):
value_mapping = {
"Product Description": "Description",
"Vendor Name": "Vendor",
"Location": "Location",
"On Hand": "Quantity",
"Reorder": "ReorderLevel",
"Delete": "Discontinued"
}
return value_mapping[input_value]
def fetch_inventory_data(description_text=None):
conn = sqlite3.connect("inventory.db")
cursor = conn.cursor()
if description_text:
cursor.execute("""
SELECT
Inventory.ItemID,
Inventory.Description,
Vendors.VendorName,
Location.Location,
Location.SubLocation,
Inventory.Quantity,
Inventory.ReorderLevel,
Inventory.Cost,
Inventory.Sell,
Inventory.Discontinued
FROM
Inventory
JOIN
Vendors ON Inventory.VendorID = Vendors.VendorID
JOIN
Location ON Inventory.LocationID = Location.LocationID
WHERE
Inventory.Description LIKE ?
ORDER BY
Inventory.Description, Vendors.VendorName;
""", ('%' + description_text + '%',))
else:
cursor.execute("""
SELECT
Inventory.ItemID,
Inventory.Description,
Vendors.VendorName,
Location.Location,
Location.SubLocation,
Inventory.Quantity,
Inventory.ReorderLevel,
Inventory.Cost,
Inventory.Sell,
Inventory.Discontinued
FROM
Inventory
JOIN
Vendors ON Inventory.VendorID = Vendors.VendorID
JOIN
Location ON Inventory.LocationID = Location.LocationID
ORDER BY
Inventory.Description, Vendors.VendorName;
""")
data = cursor.fetchall()
conn.close()
return data
def read_location_data():
conn = sqlite3.connect("inventory.db")
cursor = conn.cursor()
cursor.execute("SELECT LocationID, Location, SubLocation, Discontinued FROM Location ORDER BY Location")
data = cursor.fetchall()
conn.close()
return data
def populate_treeview():
items.delete(*items.get_children()) # Clear existing data
data = fetch_inventory_data(search_text.get())
for row in data:
cost = "${:,.2f}".format(row[7] / 100) # Index 6 corresponds to Cost
sell = "${:,.2f}".format(row[8] / 100) # Index 7 corresponds to Sell
row_list = list(row)
row_list[7] = cost
row_list[8] = sell
items.insert('', 'end', values=row_list, tags=("visible",)) # Initially mark all items as visible
def search_treeview():
populate_treeview()
sort_text.set('')
sort_text.current(0)
def reset_treeview():
search_text.delete(0,"end")
populate_treeview()
sort_text.set('')
sort_text.current(0)
def sort_treeview_up(treeview, column_name):
# Map column name to column index
column_index = treeview['columns'].index(column_name)
data = [(treeview.item(item)['values'][column_index], item) for item in treeview.get_children()]
data.sort() # Sort by specified column
for index, (value, item) in enumerate(data):
treeview.move(item, '', index)
def sort_treeview_dn(treeview, column_name):
# Map column name to column index
column_index = treeview['columns'].index(column_name)
data = [(treeview.item(item)['values'][column_index], item) for item in treeview.get_children()]
data.sort(reverse=True) # Sort by specified column in reverse order
for index, (value, item) in enumerate(data):
treeview.move(item, '', index)
def delete_discontinued_zero_quantity():
conn = sqlite3.connect("inventory.db")
c = conn.cursor()
sql_delete = """
DELETE FROM Inventory
WHERE Discontinued = 'Y' AND Quantity <= 0;
"""
c.execute(sql_delete)
conn.commit()
conn.close()
def delete_discontinued_without_inventory():
conn = sqlite3.connect("inventory.db")
c = conn.cursor()
sql_delete = """
DELETE FROM Location
WHERE Discontinued = 'Y' AND LocationID NOT IN (
SELECT LocationID FROM Inventory
);
"""
c.execute(sql_delete)
conn.commit()
conn.close()
def delete_vendors_without_inventory():
conn = sqlite3.connect("inventory.db")
c = conn.cursor()
sql_delete = """
DELETE FROM Vendors
WHERE Discontinued = 'Y' AND VendorID NOT IN (
SELECT VendorID FROM Inventory
);
"""
c.execute(sql_delete)
conn.commit()
conn.close()
def open_shortage_window():
def read_shorts_data():
conn = sqlite3.connect("inventory.db")
cursor = conn.cursor()
cursor.execute("""
SELECT
Inventory.Description,
Vendors.VendorName,
Vendors.RepName,
Vendors.RepPhone,
Inventory.Quantity
FROM
Inventory
JOIN
Vendors ON Inventory.VendorID = Vendors.VendorID
WHERE
Inventory.Quantity <= Inventory.ReorderLevel
AND
Inventory.Discontinued = 'N'
ORDER BY
Vendors.VendorName, Inventory.Description;
""")
data = cursor.fetchall()
conn.close()
return data
shorts_window = tk.Toplevel(root)
shorts_window.title("Inventory Shortage Report")
center_window(shorts_window, 1000, 400)
shorts_window.attributes("-topmost", True) # Keep the window on top
shorts_window.grab_set()
shorts_window.columnconfigure(0,weight=1)
shorts_window.rowconfigure(0,weight=1)
shorts_window.rowconfigure(1,weight=0)
shorts_frame = tk.Frame(shorts_window)
# Create Treeview widget
shorts_treeview = ttk.Treeview(shorts_frame, columns=("Description", "VendorName", "RepName", "RepPhone","Quantity"), show="headings")
shorts_treeview.heading("Description", text="Product Description")
shorts_treeview.heading("VendorName", text="Vendor Name")
shorts_treeview.heading("RepName", text="Rep Name")
shorts_treeview.heading("RepPhone", text="Rep Phone")
shorts_treeview.heading("Quantity", text="On Hand")
# Hide VendorID column
shorts_treeview["displaycolumns"] = ("Description", "VendorName", "RepName", "RepPhone", "Quantity")
# Configure individual column settings
# Configure individual column settings with minimum width
shorts_treeview.column("Description", width=250, minwidth=250, anchor="center") # Vendor Name width, centered
shorts_treeview.column("VendorName", width=250, minwidth=250, anchor="center") # Vendor Name width, centered
shorts_treeview.column("RepName", width=100, minwidth=100, anchor="center") # Rep Name width, centered
shorts_treeview.column("RepPhone", width=100, minwidth=100, anchor="center") # Rep Phone width, centered
shorts_treeview.column("Quantity", width=20, minwidth=20, anchor="center") # Delete width, centered
# Create vertical scrollbar
scrollbar = ttk.Scrollbar(shorts_frame, orient="vertical", command=shorts_treeview.yview)
# Configure Treeview to use scrollbar
shorts_treeview.configure(yscrollcommand=scrollbar.set)
# Populate Treeview with vendor data
shorts_data = read_shorts_data()
for short in shorts_data:
shorts_treeview.insert("", "end", values=short)
shorts_cancel_button=ttk.Button(shorts_window, text="Close", width=15, command=lambda: shorts_window.destroy())
# Pack
shorts_treeview.pack(side="left", fill="both", expand=True)
scrollbar.pack(side="right", fill="y")
shorts_frame.grid(row=0, column=0, sticky="nesw")
shorts_cancel_button.grid(row=1, column=0, padx = 5, pady=10)
shorts_cancel_button.focus()
def open_vendor_window():
def read_vendors_data():
conn = sqlite3.connect("inventory.db")
cursor = conn.cursor()
cursor.execute("SELECT VendorID, VendorName, RepName, RepPhone, Discontinued FROM Vendors ORDER BY VendorName")
data = cursor.fetchall()
conn.close()
return data
def populate_vendor_fields(event):
# Clear previous errors
vendor_name_text.config(foreground="")
vendor_rep_text.config(foreground="")
vendor_ph_text.config(foreground="")
# Get selected item
selected_item = vendors_treeview.selection()
if selected_item:
# Retrieve values from selected item
values = vendors_treeview.item(selected_item)['values']
# Populate entry fields
vendor_name_entry.delete(0, 'end')
vendor_name_entry.insert(0, values[1])
vendor_rep_entry.delete(0, 'end')
vendor_rep_entry.insert(0, values[2])
vendor_ph_entry.delete(0, 'end')
vendor_ph_entry.insert(0, values[3])
if values[4] == "Y":
vendor_del_var.set("Y")
else:
vendor_del_var.set("N")
def clear_vendor_fields():
# Clear entry fields
vendor_name_entry.delete(0, 'end')
vendor_rep_entry.delete(0, 'end')
vendor_ph_entry.delete(0, 'end')
vendor_del_var.set("N")
# Unselect row in treeview
vendors_treeview.selection_remove(vendors_treeview.selection())
#clear errors
vendor_name_text.config(foreground="")
vendor_rep_text.config(foreground="")
vendor_ph_text.config(foreground="")
def validate_vendor_add():
# Clear previous errors
vendor_name_text.config(foreground="")
vendor_rep_text.config(foreground="")
vendor_ph_text.config(foreground="")
# Check if fields are blank or contain only spaces
valid = True
if not vendor_name_entry.get().strip():
vendor_name_text.config(foreground="red")
valid = False
if not vendor_rep_entry.get().strip():
vendor_rep_text.config(foreground="red")
valid = False
if not vendor_ph_entry.get().strip():
vendor_ph_text.config(foreground="red")
valid = False
if valid:
confirmation = messagebox.askyesno("Confirmation Add Vendor", "Are you sure you want to add this vendor?", parent=vendor_window)
if confirmation:
add_vendor_record()
else:
messagebox.showwarning("Missing Required Information", "Please enter all required information.", parent=vendor_window)
def add_vendor_record():
conn = sqlite3.connect("inventory.db")
cursor = conn.cursor()
cursor.execute("INSERT INTO Vendors (VendorName, RepName, RepPhone, Discontinued) VALUES (?, ?, ?, ?)",
(vendor_name_entry.get().strip(), vendor_rep_entry.get().strip(),
vendor_ph_entry.get().strip(), vendor_del_var.get()))
conn.commit()
conn.close()
messagebox.showinfo("Success", "Vendor record added successfully.", parent=vendor_window)
# Refresh vendor data in Treeview
refresh_vendor_data()
def validate_vendor_modify():
selected_item = vendors_treeview.selection()
if selected_item:
# Clear previous errors
vendor_name_entry.config(foreground="")
vendor_rep_entry.config(foreground="")
vendor_ph_entry.config(foreground="")
# Check if fields are blank or contain only spaces
valid = True
if not vendor_name_entry.get().strip():
vendor_name_text.config(foreground="red")
valid = False
if not vendor_rep_entry.get().strip():
vendor_rep_text.config(foreground="red")
valid = False
if not vendor_ph_entry.get().strip():
vendor_ph_text.config(foreground="red")
valid = False
if valid:
confirmation = messagebox.askyesno("Confirmation Vendor Changes", "Are you sure you want to save changes to this vendor?", parent=vendor_window)
if confirmation:
modify_vendor_record()
else:
messagebox.showwarning("Missing Required Information", "Please enter all required information.", parent=vendor_window)
else:
messagebox.showwarning("No Vendor Selected", "Please select a vendor to modify.", parent=vendor_window)
def update_vendor_data(vendor_id, vendor_name, rep_name, rep_phone, discontinued):
conn = sqlite3.connect("inventory.db")
cursor = conn.cursor()
cursor.execute("UPDATE Vendors SET VendorName=?, RepName=?, RepPhone=?, Discontinued=? WHERE VendorID=?", (vendor_name, rep_name, rep_phone, discontinued, vendor_id))
conn.commit()
conn.close()
def modify_vendor_record():
selected_item = vendors_treeview.selection()
if selected_item:
# Get selected item
# Retrieve values from selected item
values = vendors_treeview.item(selected_item)['values']
vendor_id = values[0]
vendor_name = vendor_name_entry.get().strip()
rep_name = vendor_rep_entry.get().strip()
rep_phone = vendor_ph_entry.get().strip()
discontinued = vendor_del_var.get()
# Update vendor data
update_vendor_data(vendor_id, vendor_name, rep_name, rep_phone, discontinued)
messagebox.showinfo("Success", "Vendor updated successfully.", parent = vendor_window)
# Refresh vendor data in Treeview
refresh_vendor_data()
def refresh_vendor_data():
# Clear entry fields and errors
clear_vendor_fields()
# Reload vendor data into Treeview
vendors_treeview.delete(*vendors_treeview.get_children())
vendors_data = read_vendors_data()
for vendor in vendors_data:
vendors_treeview.insert("", "end", values=vendor)
def close_vendor_window():
reset_treeview()
vendor_window.destroy()
vendor_window = tk.Toplevel(root)
vendor_window.title("Modify Product Vendors")
center_window(vendor_window, 800, 400)
vendor_window.attributes("-topmost", True) # Keep the window on top
vendor_window.grab_set()
vendor_window.grid_columnconfigure((0, 1, 2, 3), weight=1, uniform="equal")
vendor_window.rowconfigure(0,weight=1)
vendor_window.rowconfigure(1,weight=0)
vendor_window.rowconfigure(2,weight=0)
vendor_window.rowconfigure(3,weight=0)
vendors_frame = tk.Frame(vendor_window)
# Create Treeview widget
vendors_treeview = ttk.Treeview(vendors_frame, columns=("VendorID", "VendorName", "RepName", "RepPhone","Discontinued"), show="headings")
vendors_treeview.heading("#0", text="VendorID")
vendors_treeview.heading("VendorName", text="Vendor Name")
vendors_treeview.heading("RepName", text="Rep Name")
vendors_treeview.heading("RepPhone", text="Rep Phone")
vendors_treeview.heading("Discontinued", text="Delete")
# Hide VendorID column
vendors_treeview["displaycolumns"] = ("VendorName", "RepName", "RepPhone", "Discontinued")
vendors_treeview.column("#0", width=0, stretch=False)
# Configure individual column settings
# Configure individual column settings with minimum width
vendors_treeview.column("VendorName", width=250, minwidth=250, anchor="center") # Vendor Name width, centered
vendors_treeview.column("RepName", width=110, minwidth=110, anchor="center") # Rep Name width, centered
vendors_treeview.column("RepPhone", width=100, minwidth=100, anchor="center") # Rep Phone width, centered
vendors_treeview.column("Discontinued", width=20, minwidth=20, anchor="center") # Delete width, centered
# Create vertical scrollbar
scrollbar = ttk.Scrollbar(vendors_frame, orient="vertical", command=vendors_treeview.yview)
# Configure Treeview to use scrollbar
vendors_treeview.configure(yscrollcommand=scrollbar.set)
# Populate Treeview with vendor data
vendors_data = read_vendors_data()
for vendor in vendors_data:
vendors_treeview.insert("", "end", values=vendor)
vendor_name_text=ttk.Label(vendor_window, text = "Vendor Name")
vendor_name_entry=ttk.Entry(vendor_window, width = 40)
vendor_del_text=ttk.Label(vendor_window, text="Delete")
vendor_del_var = tk.StringVar(value="N")
vendor_del_entry = ttk.Checkbutton(vendor_window, variable=vendor_del_var, onvalue="Y", offvalue="N")
vendor_rep_text=ttk.Label(vendor_window, text="Rep Name")
vendor_rep_entry=ttk.Entry(vendor_window, width = 40)
vendor_ph_text=ttk.Label(vendor_window, text="Rep Phone")
vendor_ph_entry=ttk.Entry(vendor_window, width=20)
vendor_clear_button=ttk.Button(vendor_window, text="Clear", width=15, command=clear_vendor_fields)
vendor_add_button=ttk.Button(vendor_window, text="Add Vendor", width = 15, command=validate_vendor_add)
vendor_modify_button=ttk.Button(vendor_window, text="Apply Changes", width = 15, command=validate_vendor_modify)
vendor_cancel_button=ttk.Button(vendor_window, text="Close", width=15, command=close_vendor_window)
vendors_treeview.bind('<ButtonRelease-1>', populate_vendor_fields)
# Pack
vendors_treeview.pack(side="left", fill="both", expand=True)
scrollbar.pack(side="right", fill="y")
vendors_frame.grid(row=0, column=0, columnspan=4, sticky="nesw")
vendor_name_text.grid(row=1, column=0, padx = 5, sticky="e")
vendor_name_entry.grid(row=1, column=1, sticky="w")
vendor_del_text.grid(row=1, column=2, padx = 5, sticky="e")
vendor_del_entry.grid(row=1, column=3, sticky="w")
vendor_rep_text.grid(row=2, column=0, padx = 5, sticky="e")
vendor_rep_entry.grid(row=2, column=1, sticky="w")
vendor_ph_text.grid(row=2, column=2, padx = 5, sticky="e")
vendor_ph_entry.grid(row=2, column=3, sticky="w")
vendor_cancel_button.grid(row=3, column=3, padx = 5, pady=10)
vendor_modify_button.grid(row=3, column=2, padx = 5, pady=10)
vendor_add_button.grid(row=3, column=1, padx = 5, pady=10)
vendor_clear_button.grid(row=3, column=0, padx=5, pady=10)
vendor_name_entry.focus()
def open_locations_window():
def read_locations_data():
conn = sqlite3.connect("inventory.db")
cursor = conn.cursor()
cursor.execute("SELECT LocationID, Location, SubLocation, Discontinued FROM Location ORDER BY Location")
data = cursor.fetchall()
conn.close()
return data
def populate_location_fields(event):
# Clear previous errors
location_name_text.config(foreground="")
# Get selected item
selected_item = locations_treeview.selection()
if selected_item:
# Retrieve values from selected item
values = locations_treeview.item(selected_item)['values']
# Populate entry fields
location_name_entry.delete(0, 'end')
location_name_entry.insert(0, values[1])
location_sub_entry.delete(0, 'end')
location_sub_entry.insert(0, values[2])
if values[3] == "Y":
location_del_var.set("Y")
else:
location_del_var.set("N")
def clear_location_fields():
# Clear entry fields
location_name_entry.delete(0, 'end')
location_sub_entry.delete(0, 'end')
location_del_var.set("N")
locations_treeview.selection_remove(locations_treeview.selection())
location_name_text.config(foreground="")
location_sub_text.config(foreground="")
def validate_location_add():
# Clear previous errors
location_name_text.config(foreground="")
location_sub_text.config(foreground="")
# Check if fields are blank or contain only spaces
valid = True
if not location_name_entry.get().strip():
location_name_text.config(foreground="red")
valid = False
if not location_sub_entry.get().strip():
location_sub_text.config(foreground="red")
valid = False
if valid:
confirmation = messagebox.askyesno("Confirmation Add Location", "Are you sure you want to add this location?", parent=location_window)
if confirmation:
add_location_record()
else:
messagebox.showwarning("Missing Required Information", "Please enter all required information.", parent=location_window)
def add_location_record():
conn = sqlite3.connect("inventory.db")
cursor = conn.cursor()
cursor.execute("INSERT INTO Location (Location, SubLocation, Discontinued) VALUES (?, ?, ?)",
(location_name_entry.get().strip(), location_sub_entry.get().strip(), location_del_var.get()))
conn.commit()
conn.close()
messagebox.showinfo("Success", "Location added successfully.", parent=location_window)
# Refresh location data in Treeview
refresh_location_data()
def validate_location_modify():
selected_item = locations_treeview.selection()
if selected_item:
# Clear previous errors
location_name_text.config(foreground="")
location_sub_text.config(foreground="")
# Check if fields are blank or contain only spaces
valid = True
if not location_name_entry.get().strip():
location_name_text.config(foreground="red")
valid = False
if not location_sub_entry.get().strip():
location_sub_text.config(foreground="red")
valid = False
if valid:
confirmation = messagebox.askyesno("Confirm Location Changes", "Are you sure you want to save changes to this location?", parent=location_window)
if confirmation:
modify_location_record()
else:
messagebox.showwarning("Missing Required Information", "Please enter all required information.", parent=location_window)
else:
messagebox.showwarning("No Location Selected", "Please select a location to modify.", parent=location_window)
def update_location_data(location_id, location_name, sublocation, discontinued):
conn = sqlite3.connect("inventory.db")
cursor = conn.cursor()
cursor.execute("UPDATE Location SET Location=?, SubLocation=?, Discontinued=? WHERE LocationID=?", (location_name, sublocation, discontinued, location_id))
conn.commit()
conn.close()
def modify_location_record():
selected_item = locations_treeview.selection()
if selected_item:
# Get selected item
# Retrieve values from selected item
values = locations_treeview.item(selected_item)['values']
location_id = values[0]
location_name = location_name_entry.get().strip()
sublocation = location_sub_entry.get().strip()
discontinued = location_del_var.get()
# Update location data
update_location_data(location_id, location_name, sublocation, discontinued)
messagebox.showinfo("Success", "Location updated successfully.", parent = location_window)
# Refresh location data in Treeview
refresh_location_data()
def refresh_location_data():
# Clear entry fields and errors
clear_location_fields()
# Reload location data into Treeview
locations_treeview.delete(*locations_treeview.get_children())
locations_data = read_locations_data()
for location in locations_data:
locations_treeview.insert("", "end", values=location)
def close_location_window():
reset_treeview()
location_window.destroy()
location_window = tk.Toplevel(root)
location_window.title("Modify Product Locations")
center_window(location_window, 800, 400)
location_window.attributes("-topmost", True) # Keep the window on top
location_window.grab_set()
location_window.grid_columnconfigure((0, 1, 2, 3), weight=1, uniform="equal")
location_window.rowconfigure(0,weight=1)
location_window.rowconfigure(1,weight=0)
location_window.rowconfigure(2,weight=0)
location_window.rowconfigure(3,weight=0)
locations_frame = tk.Frame(location_window)
# Create Treeview widget
locations_treeview = ttk.Treeview(locations_frame, columns=("LocationID", "Location", "SubLocation", "Discontinued"), show="headings")
locations_treeview.heading("#0", text="LocationID")
locations_treeview.heading("Location", text="Location Name")
locations_treeview.heading("SubLocation", text="Sub Location")
locations_treeview.heading("Discontinued", text="Delete")
# Hide locationID column
locations_treeview["displaycolumns"] = ("Location", "SubLocation", "Discontinued")
locations_treeview.column("#0", width=0, stretch=False)
# Configure individual column settings
# Configure individual column settings with minimum width
locations_treeview.column("Location", width=140, minwidth=140, anchor="center") # location Name width, centered
locations_treeview.column("SubLocation", width=125, minwidth=125, anchor="center") # Rep Name width, centered
locations_treeview.column("Discontinued", width=40, minwidth=40, anchor="center") # Delete width, centered
# Create vertical scrollbar
scrollbar = ttk.Scrollbar(locations_frame, orient="vertical", command=locations_treeview.yview)
# Configure Treeview to use scrollbar
locations_treeview.configure(yscrollcommand=scrollbar.set)
# Populate Treeview with location data
locations_data = read_locations_data()
for location in locations_data:
locations_treeview.insert("", "end", values=location)
location_name_text=ttk.Label(location_window, text = "Location")
location_name_entry=ttk.Entry(location_window, width = 30)
location_del_text=ttk.Label(location_window, text="Delete")
location_del_var = tk.StringVar(value="N")
location_del_entry = ttk.Checkbutton(location_window, variable=location_del_var, onvalue="Y", offvalue="N")
location_sub_text=ttk.Label(location_window, text="Sub-Location")
location_sub_entry=ttk.Entry(location_window, width = 30)
location_clear_button=ttk.Button(location_window, text="Clear", width=15, command=clear_location_fields)
location_add_button=ttk.Button(location_window, text="Add Location", width = 15, command=validate_location_add)
location_modify_button=ttk.Button(location_window, text="Apply Changes", width = 15, command=validate_location_modify)
location_cancel_button=ttk.Button(location_window, text="Close", width=15, command=close_location_window)
locations_treeview.bind('<ButtonRelease-1>', populate_location_fields)
# Pack
locations_treeview.pack(side="left", fill="both", expand=True)
scrollbar.pack(side="right", fill="y")
locations_frame.grid(row=0, column=0, columnspan=4, sticky="nesw")
location_name_text.grid(row=1, column=0, padx = 5, sticky="e")
location_name_entry.grid(row=1, column=1, sticky="w")
location_del_text.grid(row=1, column=2, padx = 5, sticky="e")
location_del_entry.grid(row=1, column=3, sticky="w")
location_sub_text.grid(row=2, column=0, padx = 5, sticky="e")
location_sub_entry.grid(row=2, column=1, sticky="w")
location_cancel_button.grid(row=3, column=3, padx = 5, pady=10)
location_modify_button.grid(row=3, column=2, padx = 5, pady=10)
location_add_button.grid(row=3, column=1, padx = 5, pady=10)
location_clear_button.grid(row=3, column=0, padx=5, pady=10)
location_name_entry.focus()
def add_item_window():
add_item_window = tk.Toplevel(root)
add_item_window.title("Add New Product")
center_window(add_item_window, 700, 400)
add_item_window.attributes("-topmost", True) # Keep the window on top
add_item_window.grab_set()
add_item_window.grid_columnconfigure((0, 1, 2), weight=1, uniform="equal")
add_item_window.grid_rowconfigure((0,1,2,3,4,5,6,7), weight=1)
add_item_window.rowconfigure(8,weight=0)
def validate_input():
# Validation for each input field
fail = False
add_item_description_label.configure(foreground="")
add_item_location_label.configure(foreground="")
add_item_vendor_label.configure(foreground="")
add_item_cost_label.configure(foreground="")
add_item_sell_label.configure(foreground="")
add_item_reorder_label.configure(foreground="")
add_item_quantity_label.configure(foreground="")
if not add_item_description_entry.get():
add_item_description_label.config(foreground="red")
fail = True
if not add_item_vendor_combobox.get():
add_item_vendor_label.config(foreground="red")
fail = True
if not add_item_location_combobox.get():
add_item_location_label.config(foreground="red")
fail = True
try:
float(add_item_cost_entry.get().replace(',', '').replace('$', '').strip())
except ValueError:
add_item_cost_label.config(foreground="red")
fail = True
try:
float(add_item_sell_entry.get().replace(',', '').replace('$', '').strip())
except ValueError:
add_item_sell_label.config(foreground="red")
fail = True
try:
int(add_item_reorder_entry.get())
except ValueError:
add_item_reorder_label.config(foreground="red")
fail =True
try:
int(add_item_quantity_entry.get())
except ValueError:
add_item_quantity_label.config(foreground="red")
fail = True
if fail :
messagebox.showwarning("Missing Required Information", "Please enter all required information.", parent=add_item_window)
return False
confirmation = messagebox.askyesno("Confirm Product Addition", "Are you sure you want to add this product?", parent=add_item_window)
if confirmation:
return True
return False
def populate_comboboxes():
# Connect to the database
conn = sqlite3.connect("inventory.db")
c = conn.cursor()
# Retrieve vendors and locations from the database
c.execute("SELECT VendorName FROM Vendors WHERE Discontinued = 'N'")
vendors = [row[0] for row in c.fetchall()]
add_item_vendor_combobox["values"] = vendors
c.execute("SELECT Location, SubLocation FROM Location WHERE Discontinued = 'N'")
locations = [f"{row[0]} - {row[1]}" if row[1] else row[0] for row in c.fetchall()]
add_item_location_combobox["values"] = locations
# Close the connection
conn.close()
def add_item():
if not validate_input():
return
# Retrieve values from the entry fields and comboboxes
description = add_item_description_entry.get()
vendor = add_item_vendor_combobox.get()
location = add_item_location_combobox.get().split(" - ")[0] # Split to get only location
cost = add_item_cost_entry.get().replace(',', '').replace('$', '').strip()
sell = add_item_sell_entry.get().replace(',', '').replace('$', '').strip()
reorder_level = add_item_reorder_entry.get().replace(',', '').strip()
discontinued = add_item_discontinued_var.get()